home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2010 April / PCWorld0410.iso / hity wydania / Ubuntu 9.10 PL / karmelkowy-koliberek-desktop-9.10-i386-PL.iso / casper / filesystem.squashfs / usr / lib / python2.6 / pydoc.pyc (.txt) < prev    next >
Python Compiled Bytecode  |  2009-11-11  |  91KB  |  2,497 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. '''Generate Python documentation in HTML or text for interactive use.
  5.  
  6. In the Python interpreter, do "from pydoc import help" to provide online
  7. help.  Calling help(thing) on a Python object documents the object.
  8.  
  9. Or, at the shell command line outside of Python:
  10.  
  11. Run "pydoc <name>" to show documentation on something.  <name> may be
  12. the name of a function, module, package, or a dotted reference to a
  13. class or function within a module or module in a package.  If the
  14. argument contains a path segment delimiter (e.g. slash on Unix,
  15. backslash on Windows) it is treated as the path to a Python source file.
  16.  
  17. Run "pydoc -k <keyword>" to search for a keyword in the synopsis lines
  18. of all available modules.
  19.  
  20. Run "pydoc -p <port>" to start an HTTP server on a given port on the
  21. local machine to generate documentation web pages.
  22.  
  23. For platforms without a command line, "pydoc -g" starts the HTTP server
  24. and also pops up a little window for controlling it.
  25.  
  26. Run "pydoc -w <name>" to write out the HTML documentation for a module
  27. to a file named "<name>.html".
  28.  
  29. Module docs for core modules are assumed to be in
  30.  
  31.     /usr/share/doc/pythonX.Y/html/library
  32.  
  33. if the pythonX.Y-doc package is installed or in
  34.  
  35.     http://docs.python.org/library/
  36.  
  37. This can be overridden by setting the PYTHONDOCS environment variable
  38. to a different URL or to a local directory containing the Library
  39. Reference Manual pages.
  40. '''
  41. __author__ = 'Ka-Ping Yee <ping@lfw.org>'
  42. __date__ = '26 February 2001'
  43. __version__ = '$Revision: 73530 $'
  44. __credits__ = 'Guido van Rossum, for an excellent programming language.\nTommy Burnette, the original creator of manpy.\nPaul Prescod, for all his work on onlinehelp.\nRichard Chamberlain, for the first implementation of textdoc.\n'
  45. import sys
  46. import imp
  47. import os
  48. import re
  49. import types
  50. import inspect
  51. import __builtin__
  52. import pkgutil
  53. from repr import Repr
  54. from string import expandtabs, find, join, lower, split, strip, rfind, rstrip
  55. from traceback import extract_tb
  56.  
  57. try:
  58.     from collections import deque
  59. except ImportError:
  60.     
  61.     class deque(list):
  62.         
  63.         def popleft(self):
  64.             return self.pop(0)
  65.  
  66.  
  67.  
  68.  
  69. def pathdirs():
  70.     '''Convert sys.path into a list of absolute, existing, unique paths.'''
  71.     dirs = []
  72.     normdirs = []
  73.     for dir in sys.path:
  74.         if not dir:
  75.             pass
  76.         dir = os.path.abspath('.')
  77.         normdir = os.path.normcase(dir)
  78.         if normdir not in normdirs and os.path.isdir(dir):
  79.             dirs.append(dir)
  80.             normdirs.append(normdir)
  81.             continue
  82.     
  83.     return dirs
  84.  
  85.  
  86. def getdoc(object):
  87.     '''Get the doc string or comments for an object.'''
  88.     if not inspect.getdoc(object):
  89.         pass
  90.     result = inspect.getcomments(object)
  91.     if not result or re.sub('^ *\n', '', rstrip(result)):
  92.         pass
  93.     return ''
  94.  
  95.  
  96. def splitdoc(doc):
  97.     '''Split a doc string into a synopsis line (if any) and the rest.'''
  98.     lines = split(strip(doc), '\n')
  99.     if len(lines) == 1:
  100.         return (lines[0], '')
  101.     if len(lines) >= 2 and not rstrip(lines[1]):
  102.         return (lines[0], join(lines[2:], '\n'))
  103.     return ('', join(lines, '\n'))
  104.  
  105.  
  106. def classname(object, modname):
  107.     '''Get a class name and qualify it with a module name if necessary.'''
  108.     name = object.__name__
  109.     if object.__module__ != modname:
  110.         name = object.__module__ + '.' + name
  111.     
  112.     return name
  113.  
  114.  
  115. def isdata(object):
  116.     """Check if an object is of a type that probably means it's data."""
  117.     if not inspect.ismodule(object) and inspect.isclass(object) and inspect.isroutine(object) and inspect.isframe(object) and inspect.istraceback(object):
  118.         pass
  119.     return not inspect.iscode(object)
  120.  
  121.  
  122. def replace(text, *pairs):
  123.     '''Do a series of global replacements on a string.'''
  124.     while pairs:
  125.         text = join(split(text, pairs[0]), pairs[1])
  126.         pairs = pairs[2:]
  127.     return text
  128.  
  129.  
  130. def cram(text, maxlen):
  131.     '''Omit part of a string if needed to make it fit in a maximum length.'''
  132.     if len(text) > maxlen:
  133.         pre = max(0, (maxlen - 3) // 2)
  134.         post = max(0, maxlen - 3 - pre)
  135.         return text[:pre] + '...' + text[len(text) - post:]
  136.     return text
  137.  
  138. _re_stripid = re.compile(' at 0x[0-9a-f]{6,16}(>+)$', re.IGNORECASE)
  139.  
  140. def stripid(text):
  141.     '''Remove the hexadecimal id from a Python object representation.'''
  142.     if _re_stripid.search(repr(Exception)):
  143.         return _re_stripid.sub('\\1', text)
  144.     return text
  145.  
  146.  
  147. def _is_some_method(obj):
  148.     if not inspect.ismethod(obj):
  149.         pass
  150.     return inspect.ismethoddescriptor(obj)
  151.  
  152.  
  153. def allmethods(cl):
  154.     methods = { }
  155.     for key, value in inspect.getmembers(cl, _is_some_method):
  156.         methods[key] = 1
  157.     
  158.     for base in cl.__bases__:
  159.         methods.update(allmethods(base))
  160.     
  161.     for key in methods.keys():
  162.         methods[key] = getattr(cl, key)
  163.     
  164.     return methods
  165.  
  166.  
  167. def _split_list(s, predicate):
  168.     '''Split sequence s via predicate, and return pair ([true], [false]).
  169.  
  170.     The return value is a 2-tuple of lists,
  171.         ([x for x in s if predicate(x)],
  172.          [x for x in s if not predicate(x)])
  173.     '''
  174.     yes = []
  175.     no = []
  176.     for x in s:
  177.         if predicate(x):
  178.             yes.append(x)
  179.             continue
  180.         no.append(x)
  181.     
  182.     return (yes, no)
  183.  
  184.  
  185. def visiblename(name, all = None):
  186.     '''Decide whether to show documentation on a variable.'''
  187.     _hidden_names = ('__builtins__', '__doc__', '__file__', '__path__', '__module__', '__name__', '__slots__', '__package__')
  188.     if name in _hidden_names:
  189.         return 0
  190.     if name.startswith('__') and name.endswith('__'):
  191.         return 1
  192.     if all is not None:
  193.         return name in all
  194.     return not name.startswith('_')
  195.  
  196.  
  197. def classify_class_attrs(object):
  198.     '''Wrap inspect.classify_class_attrs, with fixup for data descriptors.'''
  199.     
  200.     def fixup(data):
  201.         (name, kind, cls, value) = data
  202.         if inspect.isdatadescriptor(value):
  203.             kind = 'data descriptor'
  204.         
  205.         return (name, kind, cls, value)
  206.  
  207.     return map(fixup, inspect.classify_class_attrs(object))
  208.  
  209.  
  210. def ispackage(path):
  211.     '''Guess whether a path refers to a package directory.'''
  212.     if os.path.isdir(path):
  213.         for ext in ('.py', '.pyc', '.pyo'):
  214.             if os.path.isfile(os.path.join(path, '__init__' + ext)):
  215.                 return True
  216.         
  217.     
  218.     return False
  219.  
  220.  
  221. def source_synopsis(file):
  222.     line = file.readline()
  223.     while line[:1] == '#' or not strip(line):
  224.         line = file.readline()
  225.         if not line:
  226.             break
  227.             continue
  228.     line = strip(line)
  229.     if line[:4] == 'r"""':
  230.         line = line[1:]
  231.     
  232.     if line[:3] == '"""':
  233.         line = line[3:]
  234.         if line[-1:] == '\\':
  235.             line = line[:-1]
  236.         
  237.         while not strip(line):
  238.             line = file.readline()
  239.             if not line:
  240.                 break
  241.                 continue
  242.         result = strip(split(line, '"""')[0])
  243.     else:
  244.         result = None
  245.     return result
  246.  
  247.  
  248. def synopsis(filename, cache = { }):
  249.     '''Get the one-line summary out of a module file.'''
  250.     mtime = os.stat(filename).st_mtime
  251.     (lastupdate, result) = cache.get(filename, (0, None))
  252.     if lastupdate < mtime:
  253.         info = inspect.getmoduleinfo(filename)
  254.         
  255.         try:
  256.             file = open(filename)
  257.         except IOError:
  258.             return None
  259.  
  260.         if info and 'b' in info[2]:
  261.             
  262.             try:
  263.                 module = imp.load_module('__temp__', file, filename, info[1:])
  264.             except:
  265.                 return None
  266.  
  267.             if not module.__doc__:
  268.                 pass
  269.             result = ''.splitlines()[0]
  270.             del sys.modules['__temp__']
  271.         else:
  272.             result = source_synopsis(file)
  273.             file.close()
  274.         cache[filename] = (mtime, result)
  275.     
  276.     return result
  277.  
  278.  
  279. class ErrorDuringImport(Exception):
  280.     '''Errors that occurred while trying to import something to document it.'''
  281.     
  282.     def __init__(self, filename, exc_info):
  283.         (exc, value, tb) = exc_info
  284.         self.filename = filename
  285.         self.exc = exc
  286.         self.value = value
  287.         self.tb = tb
  288.  
  289.     
  290.     def __str__(self):
  291.         exc = self.exc
  292.         if type(exc) is types.ClassType:
  293.             exc = exc.__name__
  294.         
  295.         return 'problem in %s - %s: %s' % (self.filename, exc, self.value)
  296.  
  297.  
  298.  
  299. def importfile(path):
  300.     '''Import a Python source file or compiled file given its path.'''
  301.     magic = imp.get_magic()
  302.     file = open(path, 'r')
  303.     if file.read(len(magic)) == magic:
  304.         kind = imp.PY_COMPILED
  305.     else:
  306.         kind = imp.PY_SOURCE
  307.     file.close()
  308.     filename = os.path.basename(path)
  309.     (name, ext) = os.path.splitext(filename)
  310.     file = open(path, 'r')
  311.     
  312.     try:
  313.         module = imp.load_module(name, file, path, (ext, 'r', kind))
  314.     except:
  315.         raise ErrorDuringImport(path, sys.exc_info())
  316.  
  317.     file.close()
  318.     return module
  319.  
  320.  
  321. def safeimport(path, forceload = 0, cache = { }):
  322.     """Import a module; handle errors; return None if the module isn't found.
  323.  
  324.     If the module *is* found but an exception occurs, it's wrapped in an
  325.     ErrorDuringImport exception and reraised.  Unlike __import__, if a
  326.     package path is specified, the module at the end of the path is returned,
  327.     not the package at the beginning.  If the optional 'forceload' argument
  328.     is 1, we reload the module from disk (unless it's a dynamic extension)."""
  329.     
  330.     try:
  331.         if forceload and path in sys.modules:
  332.             if path not in sys.builtin_module_names:
  333.                 subs = _[1]
  334.                 for key in [
  335.                     path] + subs:
  336.                     cache[key] = sys.modules[key]
  337.                     del sys.modules[key]
  338.                 
  339.             
  340.         
  341.         module = __import__(path)
  342.     except:
  343.         (exc, value, tb) = info = sys.exc_info()
  344.         if path in sys.modules:
  345.             raise ErrorDuringImport(sys.modules[path].__file__, info)
  346.         path in sys.modules
  347.         if exc is SyntaxError:
  348.             raise ErrorDuringImport(value.filename, info)
  349.         exc is SyntaxError
  350.         if exc is ImportError and extract_tb(tb)[-1][2] == 'safeimport':
  351.             return None
  352.         raise ErrorDuringImport(path, sys.exc_info())
  353.  
  354.     for part in split(path, '.')[1:]:
  355.         
  356.         try:
  357.             module = getattr(module, part)
  358.         continue
  359.         except AttributeError:
  360.             extract_tb(tb)[-1][2] == 'safeimport'
  361.             extract_tb(tb)[-1][2] == 'safeimport'
  362.             return None
  363.         
  364.  
  365.     
  366.     return module
  367.  
  368.  
  369. class Doc:
  370.     
  371.     def document(self, object, name = None, *args):
  372.         '''Generate documentation for an object.'''
  373.         args = (object, name) + args
  374.         if inspect.isgetsetdescriptor(object):
  375.             return self.docdata(*args)
  376.         if inspect.ismemberdescriptor(object):
  377.             return self.docdata(*args)
  378.         
  379.         try:
  380.             if inspect.ismodule(object):
  381.                 return self.docmodule(*args)
  382.             if inspect.isclass(object):
  383.                 return self.docclass(*args)
  384.             if inspect.isroutine(object):
  385.                 return self.docroutine(*args)
  386.         except AttributeError:
  387.             inspect.ismemberdescriptor(object)
  388.             inspect.ismemberdescriptor(object)
  389.             inspect.isgetsetdescriptor(object)
  390.         except:
  391.             inspect.ismemberdescriptor(object)
  392.  
  393.         if isinstance(object, property):
  394.             return self.docproperty(*args)
  395.         return self.docother(*args)
  396.  
  397.     
  398.     def fail(self, object, name = None, *args):
  399.         '''Raise an exception for unimplemented types.'''
  400.         if name:
  401.             pass
  402.         message = "don't know how to document object%s of type %s" % (' ' + repr(name), type(object).__name__)
  403.         raise TypeError, message
  404.  
  405.     docmodule = docclass = docroutine = docother = docproperty = docdata = fail
  406.     
  407.     def getdocloc(self, object):
  408.         '''Return the location of module docs or None'''
  409.         
  410.         try:
  411.             file = inspect.getabsfile(object)
  412.         except TypeError:
  413.             file = '(built-in)'
  414.  
  415.         docloc = os.environ.get('PYTHONDOCS', 'http://docs.python.org/library')
  416.         docdir = '/usr/share/doc/python%s/html/library' % sys.version[:3]
  417.         if not os.environ.has_key('PYTHONDOCS') and os.path.isdir(docdir):
  418.             docloc = docdir
  419.         
  420.         basedir = os.path.join(sys.exec_prefix, 'lib', 'python' + sys.version[0:3])
  421.         if isinstance(object, type(os)):
  422.             if (object.__name__ in ('errno', 'exceptions', 'gc', 'imp', 'marshal', 'posix', 'signal', 'sys', 'thread', 'zipimport') or file.startswith(basedir)) and not file.startswith(os.path.join(basedir, 'site-packages')):
  423.                 if docloc.startswith('http://'):
  424.                     docloc = '%s/%s' % (docloc.rstrip('/'), object.__name__)
  425.                 else:
  426.                     docloc = os.path.join(docloc, object.__name__ + '.html')
  427.             else:
  428.                 docloc = None
  429.         return docloc
  430.  
  431.  
  432.  
  433. class HTMLRepr(Repr):
  434.     '''Class for safely making an HTML representation of a Python object.'''
  435.     
  436.     def __init__(self):
  437.         Repr.__init__(self)
  438.         self.maxlist = self.maxtuple = 20
  439.         self.maxdict = 10
  440.         self.maxstring = self.maxother = 100
  441.  
  442.     
  443.     def escape(self, text):
  444.         return replace(text, '&', '&', '<', '<', '>', '>')
  445.  
  446.     
  447.     def repr(self, object):
  448.         return Repr.repr(self, object)
  449.  
  450.     
  451.     def repr1(self, x, level):
  452.         if hasattr(type(x), '__name__'):
  453.             methodname = 'repr_' + join(split(type(x).__name__), '_')
  454.             if hasattr(self, methodname):
  455.                 return getattr(self, methodname)(x, level)
  456.         
  457.         return self.escape(cram(stripid(repr(x)), self.maxother))
  458.  
  459.     
  460.     def repr_string(self, x, level):
  461.         test = cram(x, self.maxstring)
  462.         testrepr = repr(test)
  463.         if '\\' in test and '\\' not in replace(testrepr, '\\\\', ''):
  464.             return 'r' + testrepr[0] + self.escape(test) + testrepr[0]
  465.         return re.sub('((\\\\[\\\\abfnrtv\\\'"]|\\\\[0-9]..|\\\\x..|\\\\u....)+)', '<font color="#c040c0">\\1</font>', self.escape(testrepr))
  466.  
  467.     repr_str = repr_string
  468.     
  469.     def repr_instance(self, x, level):
  470.         
  471.         try:
  472.             return self.escape(cram(stripid(repr(x)), self.maxstring))
  473.         except:
  474.             return self.escape('<%s instance>' % x.__class__.__name__)
  475.  
  476.  
  477.     repr_unicode = repr_string
  478.  
  479.  
  480. class HTMLDoc(Doc):
  481.     '''Formatter class for HTML documentation.'''
  482.     _repr_instance = HTMLRepr()
  483.     repr = _repr_instance.repr
  484.     escape = _repr_instance.escape
  485.     
  486.     def page(self, title, contents):
  487.         '''Format an HTML page.'''
  488.         return '\n<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">\n<html><head><title>Python: %s</title>\n</head><body bgcolor="#f0f0f8">\n%s\n</body></html>' % (title, contents)
  489.  
  490.     
  491.     def heading(self, title, fgcol, bgcol, extras = ''):
  492.         '''Format a page heading.'''
  493.         if not extras:
  494.             pass
  495.         return '\n<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="heading">\n<tr bgcolor="%s">\n<td valign=bottom> <br>\n<font color="%s" face="helvetica, arial"> <br>%s</font></td\n><td align=right valign=bottom\n><font color="%s" face="helvetica, arial">%s</font></td></tr></table>\n    ' % (bgcol, fgcol, title, fgcol, ' ')
  496.  
  497.     
  498.     def section(self, title, fgcol, bgcol, contents, width = 6, prelude = '', marginalia = None, gap = ' '):
  499.         '''Format a section with a heading.'''
  500.         if marginalia is None:
  501.             marginalia = '<tt>' + ' ' * width + '</tt>'
  502.         
  503.         result = '<p>\n<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">\n<tr bgcolor="%s">\n<td colspan=3 valign=bottom> <br>\n<font color="%s" face="helvetica, arial">%s</font></td></tr>\n    ' % (bgcol, fgcol, title)
  504.         if prelude:
  505.             result = result + '\n<tr bgcolor="%s"><td rowspan=2>%s</td>\n<td colspan=2>%s</td></tr>\n<tr><td>%s</td>' % (bgcol, marginalia, prelude, gap)
  506.         else:
  507.             result = result + '\n<tr><td bgcolor="%s">%s</td><td>%s</td>' % (bgcol, marginalia, gap)
  508.         return result + '\n<td width="100%%">%s</td></tr></table>' % contents
  509.  
  510.     
  511.     def bigsection(self, title, *args):
  512.         '''Format a section with a big heading.'''
  513.         title = '<big><strong>%s</strong></big>' % title
  514.         return self.section(title, *args)
  515.  
  516.     
  517.     def preformat(self, text):
  518.         '''Format literal preformatted text.'''
  519.         text = self.escape(expandtabs(text))
  520.         return replace(text, '\n\n', '\n \n', '\n\n', '\n \n', ' ', ' ', '\n', '<br>\n')
  521.  
  522.     
  523.     def multicolumn(self, list, format, cols = 4):
  524.         '''Format a list of items into a multi-column list.'''
  525.         result = ''
  526.         rows = (len(list) + cols - 1) / cols
  527.         for col in range(cols):
  528.             result = result + '<td width="%d%%" valign=top>' % 100 / cols
  529.             for i in range(rows * col, rows * col + rows):
  530.                 if i < len(list):
  531.                     result = result + format(list[i]) + '<br>\n'
  532.                     continue
  533.             
  534.             result = result + '</td>'
  535.         
  536.         return '<table width="100%%" summary="list"><tr>%s</tr></table>' % result
  537.  
  538.     
  539.     def grey(self, text):
  540.         return '<font color="#909090">%s</font>' % text
  541.  
  542.     
  543.     def namelink(self, name, *dicts):
  544.         '''Make a link for an identifier, given name-to-URL mappings.'''
  545.         for dict in dicts:
  546.             if name in dict:
  547.                 return '<a href="%s">%s</a>' % (dict[name], name)
  548.         
  549.         return name
  550.  
  551.     
  552.     def classlink(self, object, modname):
  553.         '''Make a link for a class.'''
  554.         name = object.__name__
  555.         module = sys.modules.get(object.__module__)
  556.         if hasattr(module, name) and getattr(module, name) is object:
  557.             return '<a href="%s.html#%s">%s</a>' % (module.__name__, name, classname(object, modname))
  558.         return classname(object, modname)
  559.  
  560.     
  561.     def modulelink(self, object):
  562.         '''Make a link for a module.'''
  563.         return '<a href="%s.html">%s</a>' % (object.__name__, object.__name__)
  564.  
  565.     
  566.     def modpkglink(self, data):
  567.         '''Make a link for a module or package to display in an index.'''
  568.         (name, path, ispackage, shadowed) = data
  569.         if shadowed:
  570.             return self.grey(name)
  571.         if path:
  572.             url = '%s.%s.html' % (path, name)
  573.         else:
  574.             url = '%s.html' % name
  575.         if ispackage:
  576.             text = '<strong>%s</strong> (package)' % name
  577.         else:
  578.             text = name
  579.         return '<a href="%s">%s</a>' % (url, text)
  580.  
  581.     
  582.     def markup(self, text, escape = None, funcs = { }, classes = { }, methods = { }):
  583.         '''Mark up some plain text, given a context of symbols to look for.
  584.         Each context dictionary maps object names to anchor names.'''
  585.         if not escape:
  586.             pass
  587.         escape = self.escape
  588.         results = []
  589.         here = 0
  590.         pattern = re.compile('\\b((http|ftp)://\\S+[\\w/]|RFC[- ]?(\\d+)|PEP[- ]?(\\d+)|(self\\.)?(\\w+))')
  591.         while True:
  592.             match = pattern.search(text, here)
  593.             if not match:
  594.                 break
  595.             
  596.             (start, end) = match.span()
  597.             results.append(escape(text[here:start]))
  598.             (all, scheme, rfc, pep, selfdot, name) = match.groups()
  599.             if scheme:
  600.                 url = escape(all).replace('"', '"')
  601.                 results.append('<a href="%s">%s</a>' % (url, url))
  602.             elif rfc:
  603.                 url = 'http://www.rfc-editor.org/rfc/rfc%d.txt' % int(rfc)
  604.                 results.append('<a href="%s">%s</a>' % (url, escape(all)))
  605.             elif pep:
  606.                 url = 'http://www.python.org/dev/peps/pep-%04d/' % int(pep)
  607.                 results.append('<a href="%s">%s</a>' % (url, escape(all)))
  608.             elif text[end:end + 1] == '(':
  609.                 results.append(self.namelink(name, methods, funcs, classes))
  610.             elif selfdot:
  611.                 results.append('self.<strong>%s</strong>' % name)
  612.             else:
  613.                 results.append(self.namelink(name, classes))
  614.             here = end
  615.         results.append(escape(text[here:]))
  616.         return join(results, '')
  617.  
  618.     
  619.     def formattree(self, tree, modname, parent = None):
  620.         '''Produce HTML for a class tree as given by inspect.getclasstree().'''
  621.         result = ''
  622.         for entry in tree:
  623.             if type(entry) is type(()):
  624.                 (c, bases) = entry
  625.                 result = result + '<dt><font face="helvetica, arial">'
  626.                 result = result + self.classlink(c, modname)
  627.                 if bases and bases != (parent,):
  628.                     parents = []
  629.                     for base in bases:
  630.                         parents.append(self.classlink(base, modname))
  631.                     
  632.                     result = result + '(' + join(parents, ', ') + ')'
  633.                 
  634.                 result = result + '\n</font></dt>'
  635.                 continue
  636.             if type(entry) is type([]):
  637.                 result = result + '<dd>\n%s</dd>\n' % self.formattree(entry, modname, c)
  638.                 continue
  639.         
  640.         return '<dl>\n%s</dl>\n' % result
  641.  
  642.     
  643.     def docmodule(self, object, name = None, mod = None, *ignored):
  644.         '''Produce HTML documentation for a module object.'''
  645.         name = object.__name__
  646.         
  647.         try:
  648.             all = object.__all__
  649.         except AttributeError:
  650.             all = None
  651.  
  652.         parts = split(name, '.')
  653.         links = []
  654.         for i in range(len(parts) - 1):
  655.             links.append('<a href="%s.html"><font color="#ffffff">%s</font></a>' % (join(parts[:i + 1], '.'), parts[i]))
  656.         
  657.         linkedname = join(links + parts[-1:], '.')
  658.         head = '<big><big><strong>%s</strong></big></big>' % linkedname
  659.         
  660.         try:
  661.             path = inspect.getabsfile(object)
  662.             url = path
  663.             if sys.platform == 'win32':
  664.                 import nturl2path as nturl2path
  665.                 url = nturl2path.pathname2url(path)
  666.             
  667.             filelink = '<a href="file:%s">%s</a>' % (url, path)
  668.         except TypeError:
  669.             filelink = '(built-in)'
  670.  
  671.         info = []
  672.         if hasattr(object, '__version__'):
  673.             version = str(object.__version__)
  674.             if version[:11] == '$Revision: ' and version[-1:] == '$':
  675.                 version = strip(version[11:-1])
  676.             
  677.             info.append('version %s' % self.escape(version))
  678.         
  679.         if hasattr(object, '__date__'):
  680.             info.append(self.escape(str(object.__date__)))
  681.         
  682.         if info:
  683.             head = head + ' (%s)' % join(info, ', ')
  684.         
  685.         docloc = self.getdocloc(object)
  686.         if docloc is not None:
  687.             docloc = '<br><a href="%(docloc)s">Module Docs</a>' % locals()
  688.         else:
  689.             docloc = ''
  690.         result = self.heading(head, '#ffffff', '#7799ee', '<a href=".">index</a><br>' + filelink + docloc)
  691.         modules = inspect.getmembers(object, inspect.ismodule)
  692.         classes = []
  693.         cdict = { }
  694.         for key, value in inspect.getmembers(object, inspect.isclass):
  695.             if not all is not None:
  696.                 pass
  697.             None if not inspect.getmodule(value) else visiblename(key, all)
  698.         
  699.         for key, value in classes:
  700.             for base in value.__bases__:
  701.                 key = base.__name__
  702.                 modname = base.__module__
  703.                 module = sys.modules.get(modname)
  704.                 if modname != name and module and hasattr(module, key):
  705.                     if getattr(module, key) is base:
  706.                         if key not in cdict:
  707.                             cdict[key] = cdict[base] = modname + '.html#' + key
  708.                         
  709.                     
  710.                 getattr(module, key) is base
  711.             
  712.         
  713.         funcs = []
  714.         fdict = { }
  715.         for key, value in inspect.getmembers(object, inspect.isroutine):
  716.             if all is not None and inspect.isbuiltin(value) or inspect.getmodule(value) is object:
  717.                 if visiblename(key, all):
  718.                     funcs.append((key, value))
  719.                     fdict[key] = '#-' + key
  720.                     if inspect.isfunction(value):
  721.                         fdict[value] = fdict[key]
  722.                     
  723.                 
  724.             visiblename(key, all)
  725.         
  726.         data = []
  727.         for key, value in inspect.getmembers(object, isdata):
  728.             if visiblename(key, all):
  729.                 data.append((key, value))
  730.                 continue
  731.         
  732.         doc = self.markup(getdoc(object), self.preformat, fdict, cdict)
  733.         if doc:
  734.             pass
  735.         doc = '<tt>%s</tt>' % doc
  736.         result = result + '<p>%s</p>\n' % doc
  737.         if hasattr(object, '__path__'):
  738.             modpkgs = []
  739.             for importer, modname, ispkg in pkgutil.iter_modules(object.__path__):
  740.                 modpkgs.append((modname, name, ispkg, 0))
  741.             
  742.             modpkgs.sort()
  743.             contents = self.multicolumn(modpkgs, self.modpkglink)
  744.             result = result + self.bigsection('Package Contents', '#ffffff', '#aa55cc', contents)
  745.         elif modules:
  746.             contents = self.multicolumn(modules, (lambda key_value, s = self: s.modulelink(key_value[1])))
  747.             result = result + self.bigsection('Modules', '#ffffff', '#aa55cc', contents)
  748.         
  749.         if classes:
  750.             classlist = map((lambda key_value: key_value[1]), classes)
  751.             contents = [
  752.                 self.formattree(inspect.getclasstree(classlist, 1), name)]
  753.             for key, value in classes:
  754.                 contents.append(self.document(value, key, name, fdict, cdict))
  755.             
  756.             result = result + self.bigsection('Classes', '#ffffff', '#ee77aa', join(contents))
  757.         
  758.         if funcs:
  759.             contents = []
  760.             for key, value in funcs:
  761.                 contents.append(self.document(value, key, name, fdict, cdict))
  762.             
  763.             result = result + self.bigsection('Functions', '#ffffff', '#eeaa77', join(contents))
  764.         
  765.         if data:
  766.             contents = []
  767.             for key, value in data:
  768.                 contents.append(self.document(value, key))
  769.             
  770.             result = result + self.bigsection('Data', '#ffffff', '#55aa55', join(contents, '<br>\n'))
  771.         
  772.         if hasattr(object, '__author__'):
  773.             contents = self.markup(str(object.__author__), self.preformat)
  774.             result = result + self.bigsection('Author', '#ffffff', '#7799ee', contents)
  775.         
  776.         if hasattr(object, '__credits__'):
  777.             contents = self.markup(str(object.__credits__), self.preformat)
  778.             result = result + self.bigsection('Credits', '#ffffff', '#7799ee', contents)
  779.         
  780.         return result
  781.  
  782.     
  783.     def docclass(self, object, name = None, mod = None, funcs = { }, classes = { }, *ignored):
  784.         '''Produce HTML documentation for a class object.'''
  785.         realname = object.__name__
  786.         if not name:
  787.             pass
  788.         name = realname
  789.         bases = object.__bases__
  790.         contents = []
  791.         push = contents.append
  792.         
  793.         class HorizontalRule(()):
  794.             
  795.             def __init__(self):
  796.                 self.needone = 0
  797.  
  798.             
  799.             def maybe(self):
  800.                 if self.needone:
  801.                     push('<hr>\n')
  802.                 
  803.                 self.needone = 1
  804.  
  805.  
  806.         hr = HorizontalRule()
  807.         mro = deque(inspect.getmro(object))
  808.         if len(mro) > 2:
  809.             hr.maybe()
  810.             push('<dl><dt>Method resolution order:</dt>\n')
  811.             for base in mro:
  812.                 push('<dd>%s</dd>\n' % self.classlink(base, object.__module__))
  813.             
  814.             push('</dl>\n')
  815.         
  816.         
  817.         def spill(msg, attrs, predicate):
  818.             (ok, attrs) = _split_list(attrs, predicate)
  819.             if ok:
  820.                 hr.maybe()
  821.                 push(msg)
  822.                 for name, kind, homecls, value in ok:
  823.                     push(self.document(getattr(object, name), name, mod, funcs, classes, mdict, object))
  824.                     push('\n')
  825.                 
  826.             
  827.             return attrs
  828.  
  829.         
  830.         def spilldescriptors(msg, attrs, predicate):
  831.             (ok, attrs) = _split_list(attrs, predicate)
  832.             if ok:
  833.                 hr.maybe()
  834.                 push(msg)
  835.                 for name, kind, homecls, value in ok:
  836.                     push(self._docdescriptor(name, value, mod))
  837.                 
  838.             
  839.             return attrs
  840.  
  841.         
  842.         def spilldata(msg, attrs, predicate):
  843.             (ok, attrs) = _split_list(attrs, predicate)
  844.             if ok:
  845.                 hr.maybe()
  846.                 push(msg)
  847.                 for name, kind, homecls, value in ok:
  848.                     base = self.docother(getattr(object, name), name, mod)
  849.                     if hasattr(value, '__call__') or inspect.isdatadescriptor(value):
  850.                         doc = getattr(value, '__doc__', None)
  851.                     else:
  852.                         doc = None
  853.                     if doc is None:
  854.                         push('<dl><dt>%s</dl>\n' % base)
  855.                     else:
  856.                         doc = self.markup(getdoc(value), self.preformat, funcs, classes, mdict)
  857.                         doc = '<dd><tt>%s</tt>' % doc
  858.                         push('<dl><dt>%s%s</dl>\n' % (base, doc))
  859.                     push('\n')
  860.                 
  861.             
  862.             return attrs
  863.  
  864.         attrs = filter((lambda data: visiblename(data[0])), classify_class_attrs(object))
  865.         mdict = { }
  866.         for key, kind, homecls, value in attrs:
  867.             value = getattr(object, key)
  868.             
  869.             try:
  870.                 mdict[value] = anchor
  871.             continue
  872.             except TypeError:
  873.                 (None, None, None, None, None, None, None, (None, None, None, (None, None, None, None, None, None, None, None)))
  874.                 (None, None, None, None, None, None, None, (None, None, None, (None, None, None, None, None, None, None, None)))
  875.                 continue
  876.             
  877.  
  878.         
  879.         while attrs:
  880.             (attrs, inherited) = _split_list((attrs,), (lambda t: t[2] is thisclass))
  881.             if thisclass is __builtin__.object:
  882.                 attrs = inherited
  883.                 continue
  884.             elif thisclass is object:
  885.                 tag = 'defined here'
  886.             else:
  887.                 tag = 'inherited from %s' % self.classlink(thisclass, object.__module__)
  888.             tag += ':<br>\n'
  889.             
  890.             try:
  891.                 attrs.sort(key = (lambda t: t[0]))
  892.             except TypeError:
  893.                 attrs.sort((lambda t1, t2: cmp(t1[0], t2[0])))
  894.  
  895.             attrs = spill('Methods %s' % tag, attrs, (lambda t: t[1] == 'method'))
  896.             attrs = spill('Class methods %s' % tag, attrs, (lambda t: t[1] == 'class method'))
  897.             attrs = spill('Static methods %s' % tag, attrs, (lambda t: t[1] == 'static method'))
  898.             attrs = spilldescriptors('Data descriptors %s' % tag, attrs, (lambda t: t[1] == 'data descriptor'))
  899.             attrs = spilldata('Data and other attributes %s' % tag, attrs, (lambda t: t[1] == 'data'))
  900.             if not attrs == []:
  901.                 raise AssertionError
  902.             attrs = inherited
  903.             continue
  904.             attrs == []
  905.         contents = ''.join(contents)
  906.         if name == realname:
  907.             title = '<a name="%s">class <strong>%s</strong></a>' % (name, realname)
  908.         else:
  909.             title = '<strong>%s</strong> = <a name="%s">class %s</a>' % (name, name, realname)
  910.         if bases:
  911.             parents = []
  912.             for base in bases:
  913.                 parents.append(self.classlink(base, object.__module__))
  914.             
  915.             title = title + '(%s)' % join(parents, ', ')
  916.         
  917.         doc = self.markup(getdoc(object), self.preformat, funcs, classes, mdict)
  918.         if doc:
  919.             pass
  920.         doc = '<tt>%s<br> </tt>' % doc
  921.         return self.section(title, '#000000', '#ffc8d8', contents, 3, doc)
  922.  
  923.     
  924.     def formatvalue(self, object):
  925.         '''Format an argument default value as text.'''
  926.         return self.grey('=' + self.repr(object))
  927.  
  928.     
  929.     def docroutine(self, object, name = None, mod = None, funcs = { }, classes = { }, methods = { }, cl = None):
  930.         '''Produce HTML documentation for a function or method object.'''
  931.         realname = object.__name__
  932.         if not name:
  933.             pass
  934.         name = realname
  935.         if not cl or cl.__name__:
  936.             pass
  937.         anchor = '' + '-' + name
  938.         note = ''
  939.         skipdocs = 0
  940.         if inspect.ismethod(object):
  941.             imclass = object.im_class
  942.             if cl:
  943.                 if imclass is not cl:
  944.                     note = ' from ' + self.classlink(imclass, mod)
  945.                 
  946.             elif object.im_self is not None:
  947.                 note = ' method of %s instance' % self.classlink(object.im_self.__class__, mod)
  948.             else:
  949.                 note = ' unbound %s method' % self.classlink(imclass, mod)
  950.             object = object.im_func
  951.         
  952.         if name == realname:
  953.             title = '<a name="%s"><strong>%s</strong></a>' % (anchor, realname)
  954.         elif cl and realname in cl.__dict__ and cl.__dict__[realname] is object:
  955.             reallink = '<a href="#%s">%s</a>' % (cl.__name__ + '-' + realname, realname)
  956.             skipdocs = 1
  957.         else:
  958.             reallink = realname
  959.         title = '<a name="%s"><strong>%s</strong></a> = %s' % (anchor, name, reallink)
  960.         if inspect.isfunction(object):
  961.             (args, varargs, varkw, defaults) = inspect.getargspec(object)
  962.             argspec = inspect.formatargspec(args, varargs, varkw, defaults, formatvalue = self.formatvalue)
  963.             if realname == '<lambda>':
  964.                 title = '<strong>%s</strong> <em>lambda</em> ' % name
  965.                 argspec = argspec[1:-1]
  966.             
  967.         else:
  968.             argspec = '(...)'
  969.         if note:
  970.             pass
  971.         decl = title + argspec + self.grey('<font face="helvetica, arial">%s</font>' % note)
  972.         if skipdocs:
  973.             return '<dl><dt>%s</dt></dl>\n' % decl
  974.         doc = self.markup(getdoc(object), self.preformat, funcs, classes, methods)
  975.         if doc:
  976.             pass
  977.         doc = '<dd><tt>%s</tt></dd>' % doc
  978.         return '<dl><dt>%s</dt>%s</dl>\n' % (decl, doc)
  979.  
  980.     
  981.     def _docdescriptor(self, name, value, mod):
  982.         results = []
  983.         push = results.append
  984.         if name:
  985.             push('<dl><dt><strong>%s</strong></dt>\n' % name)
  986.         
  987.         if value.__doc__ is not None:
  988.             doc = self.markup(getdoc(value), self.preformat)
  989.             push('<dd><tt>%s</tt></dd>\n' % doc)
  990.         
  991.         push('</dl>\n')
  992.         return ''.join(results)
  993.  
  994.     
  995.     def docproperty(self, object, name = None, mod = None, cl = None):
  996.         '''Produce html documentation for a property.'''
  997.         return self._docdescriptor(name, object, mod)
  998.  
  999.     
  1000.     def docother(self, object, name = None, mod = None, *ignored):
  1001.         '''Produce HTML documentation for a data object.'''
  1002.         if not name or '<strong>%s</strong> = ' % name:
  1003.             pass
  1004.         lhs = ''
  1005.         return lhs + self.repr(object)
  1006.  
  1007.     
  1008.     def docdata(self, object, name = None, mod = None, cl = None):
  1009.         '''Produce html documentation for a data descriptor.'''
  1010.         return self._docdescriptor(name, object, mod)
  1011.  
  1012.     
  1013.     def index(self, dir, shadowed = None):
  1014.         '''Generate an HTML index for a directory of modules.'''
  1015.         modpkgs = []
  1016.         if shadowed is None:
  1017.             shadowed = { }
  1018.         
  1019.         for importer, name, ispkg in pkgutil.iter_modules([
  1020.             dir]):
  1021.             modpkgs.append((name, '', ispkg, name in shadowed))
  1022.             shadowed[name] = 1
  1023.         
  1024.         modpkgs.sort()
  1025.         contents = self.multicolumn(modpkgs, self.modpkglink)
  1026.         return self.bigsection(dir, '#ffffff', '#ee77aa', contents)
  1027.  
  1028.  
  1029.  
  1030. class TextRepr(Repr):
  1031.     '''Class for safely making a text representation of a Python object.'''
  1032.     
  1033.     def __init__(self):
  1034.         Repr.__init__(self)
  1035.         self.maxlist = self.maxtuple = 20
  1036.         self.maxdict = 10
  1037.         self.maxstring = self.maxother = 100
  1038.  
  1039.     
  1040.     def repr1(self, x, level):
  1041.         if hasattr(type(x), '__name__'):
  1042.             methodname = 'repr_' + join(split(type(x).__name__), '_')
  1043.             if hasattr(self, methodname):
  1044.                 return getattr(self, methodname)(x, level)
  1045.         
  1046.         return cram(stripid(repr(x)), self.maxother)
  1047.  
  1048.     
  1049.     def repr_string(self, x, level):
  1050.         test = cram(x, self.maxstring)
  1051.         testrepr = repr(test)
  1052.         if '\\' in test and '\\' not in replace(testrepr, '\\\\', ''):
  1053.             return 'r' + testrepr[0] + test + testrepr[0]
  1054.         return testrepr
  1055.  
  1056.     repr_str = repr_string
  1057.     
  1058.     def repr_instance(self, x, level):
  1059.         
  1060.         try:
  1061.             return cram(stripid(repr(x)), self.maxstring)
  1062.         except:
  1063.             return '<%s instance>' % x.__class__.__name__
  1064.  
  1065.  
  1066.  
  1067.  
  1068. class TextDoc(Doc):
  1069.     '''Formatter class for text documentation.'''
  1070.     _repr_instance = TextRepr()
  1071.     repr = _repr_instance.repr
  1072.     
  1073.     def bold(self, text):
  1074.         '''Format a string in bold by overstriking.'''
  1075.         return join(map((lambda ch: ch + '\x08' + ch), text), '')
  1076.  
  1077.     
  1078.     def indent(self, text, prefix = '    '):
  1079.         '''Indent text by prepending a given prefix to each line.'''
  1080.         if not text:
  1081.             return ''
  1082.         lines = split(text, '\n')
  1083.         lines = map((lambda line, prefix = prefix: prefix + line), lines)
  1084.         if lines:
  1085.             lines[-1] = rstrip(lines[-1])
  1086.         
  1087.         return join(lines, '\n')
  1088.  
  1089.     
  1090.     def section(self, title, contents):
  1091.         '''Format a section with a given heading.'''
  1092.         return self.bold(title) + '\n' + rstrip(self.indent(contents)) + '\n\n'
  1093.  
  1094.     
  1095.     def formattree(self, tree, modname, parent = None, prefix = ''):
  1096.         '''Render in text a class tree as returned by inspect.getclasstree().'''
  1097.         result = ''
  1098.         for entry in tree:
  1099.             if type(entry) is type(()):
  1100.                 (c, bases) = entry
  1101.                 result = result + prefix + classname(c, modname)
  1102.                 if bases and bases != (parent,):
  1103.                     parents = map((lambda c, m = modname: classname(c, m)), bases)
  1104.                     result = result + '(%s)' % join(parents, ', ')
  1105.                 
  1106.                 result = result + '\n'
  1107.                 continue
  1108.             if type(entry) is type([]):
  1109.                 result = result + self.formattree(entry, modname, c, prefix + '    ')
  1110.                 continue
  1111.         
  1112.         return result
  1113.  
  1114.     
  1115.     def docmodule(self, object, name = None, mod = None):
  1116.         '''Produce text documentation for a given module object.'''
  1117.         name = object.__name__
  1118.         (synop, desc) = splitdoc(getdoc(object))
  1119.         if synop:
  1120.             pass
  1121.         result = self.section('NAME', name + ' - ' + synop)
  1122.         
  1123.         try:
  1124.             all = object.__all__
  1125.         except AttributeError:
  1126.             all = None
  1127.  
  1128.         
  1129.         try:
  1130.             file = inspect.getabsfile(object)
  1131.         except TypeError:
  1132.             file = '(built-in)'
  1133.  
  1134.         result = result + self.section('FILE', file)
  1135.         docloc = self.getdocloc(object)
  1136.         if docloc is not None:
  1137.             result = result + self.section('MODULE DOCS', docloc)
  1138.         
  1139.         if desc:
  1140.             result = result + self.section('DESCRIPTION', desc)
  1141.         
  1142.         classes = []
  1143.         for key, value in inspect.getmembers(object, inspect.isclass):
  1144.             if not all is not None:
  1145.                 pass
  1146.             None if not inspect.getmodule(value) else visiblename(key, all)
  1147.         
  1148.         funcs = []
  1149.         for key, value in inspect.getmembers(object, inspect.isroutine):
  1150.             if all is not None and inspect.isbuiltin(value) or inspect.getmodule(value) is object:
  1151.                 if visiblename(key, all):
  1152.                     funcs.append((key, value))
  1153.                 
  1154.             visiblename(key, all)
  1155.         
  1156.         data = []
  1157.         for key, value in inspect.getmembers(object, isdata):
  1158.             if visiblename(key, all):
  1159.                 data.append((key, value))
  1160.                 continue
  1161.         
  1162.         modpkgs = []
  1163.         modpkgs_names = set()
  1164.         if hasattr(object, '__path__'):
  1165.             for importer, modname, ispkg in pkgutil.iter_modules(object.__path__):
  1166.                 modpkgs_names.add(modname)
  1167.                 if ispkg:
  1168.                     modpkgs.append(modname + ' (package)')
  1169.                     continue
  1170.                 modpkgs.append(modname)
  1171.             
  1172.             modpkgs.sort()
  1173.             result = result + self.section('PACKAGE CONTENTS', join(modpkgs, '\n'))
  1174.         
  1175.         submodules = []
  1176.         for key, value in inspect.getmembers(object, inspect.ismodule):
  1177.             if value.__name__.startswith(name + '.') and key not in modpkgs_names:
  1178.                 submodules.append(key)
  1179.                 continue
  1180.         
  1181.         if submodules:
  1182.             submodules.sort()
  1183.             result = result + self.section('SUBMODULES', join(submodules, '\n'))
  1184.         
  1185.         if classes:
  1186.             classlist = map((lambda key_value: key_value[1]), classes)
  1187.             contents = [
  1188.                 self.formattree(inspect.getclasstree(classlist, 1), name)]
  1189.             for key, value in classes:
  1190.                 contents.append(self.document(value, key, name))
  1191.             
  1192.             result = result + self.section('CLASSES', join(contents, '\n'))
  1193.         
  1194.         if funcs:
  1195.             contents = []
  1196.             for key, value in funcs:
  1197.                 contents.append(self.document(value, key, name))
  1198.             
  1199.             result = result + self.section('FUNCTIONS', join(contents, '\n'))
  1200.         
  1201.         if data:
  1202.             contents = []
  1203.             for key, value in data:
  1204.                 contents.append(self.docother(value, key, name, maxlen = 70))
  1205.             
  1206.             result = result + self.section('DATA', join(contents, '\n'))
  1207.         
  1208.         if hasattr(object, '__version__'):
  1209.             version = str(object.__version__)
  1210.             if version[:11] == '$Revision: ' and version[-1:] == '$':
  1211.                 version = strip(version[11:-1])
  1212.             
  1213.             result = result + self.section('VERSION', version)
  1214.         
  1215.         if hasattr(object, '__date__'):
  1216.             result = result + self.section('DATE', str(object.__date__))
  1217.         
  1218.         if hasattr(object, '__author__'):
  1219.             result = result + self.section('AUTHOR', str(object.__author__))
  1220.         
  1221.         if hasattr(object, '__credits__'):
  1222.             result = result + self.section('CREDITS', str(object.__credits__))
  1223.         
  1224.         return result
  1225.  
  1226.     
  1227.     def docclass(self, object, name = None, mod = None):
  1228.         '''Produce text documentation for a given class object.'''
  1229.         realname = object.__name__
  1230.         if not name:
  1231.             pass
  1232.         name = realname
  1233.         bases = object.__bases__
  1234.         
  1235.         def makename(c, m = object.__module__):
  1236.             return classname(c, m)
  1237.  
  1238.         if name == realname:
  1239.             title = 'class ' + self.bold(realname)
  1240.         else:
  1241.             title = self.bold(name) + ' = class ' + realname
  1242.         if bases:
  1243.             parents = map(makename, bases)
  1244.             title = title + '(%s)' % join(parents, ', ')
  1245.         
  1246.         doc = getdoc(object)
  1247.         if not doc or [
  1248.             doc + '\n']:
  1249.             pass
  1250.         contents = []
  1251.         push = contents.append
  1252.         mro = deque(inspect.getmro(object))
  1253.         if len(mro) > 2:
  1254.             push('Method resolution order:')
  1255.             for base in mro:
  1256.                 push('    ' + makename(base))
  1257.             
  1258.             push('')
  1259.         
  1260.         
  1261.         class HorizontalRule(()):
  1262.             
  1263.             def __init__(self):
  1264.                 self.needone = 0
  1265.  
  1266.             
  1267.             def maybe(self):
  1268.                 if self.needone:
  1269.                     push('-' * 70)
  1270.                 
  1271.                 self.needone = 1
  1272.  
  1273.  
  1274.         hr = HorizontalRule()
  1275.         
  1276.         def spill(msg, attrs, predicate):
  1277.             (ok, attrs) = _split_list(attrs, predicate)
  1278.             if ok:
  1279.                 hr.maybe()
  1280.                 push(msg)
  1281.                 for name, kind, homecls, value in ok:
  1282.                     push(self.document(getattr(object, name), name, mod, object))
  1283.                 
  1284.             
  1285.             return attrs
  1286.  
  1287.         
  1288.         def spilldescriptors(msg, attrs, predicate):
  1289.             (ok, attrs) = _split_list(attrs, predicate)
  1290.             if ok:
  1291.                 hr.maybe()
  1292.                 push(msg)
  1293.                 for name, kind, homecls, value in ok:
  1294.                     push(self._docdescriptor(name, value, mod))
  1295.                 
  1296.             
  1297.             return attrs
  1298.  
  1299.         
  1300.         def spilldata(msg, attrs, predicate):
  1301.             (ok, attrs) = _split_list(attrs, predicate)
  1302.             if ok:
  1303.                 hr.maybe()
  1304.                 push(msg)
  1305.                 for name, kind, homecls, value in ok:
  1306.                     if hasattr(value, '__call__') or inspect.isdatadescriptor(value):
  1307.                         doc = getdoc(value)
  1308.                     else:
  1309.                         doc = None
  1310.                     push(self.docother(getattr(object, name), name, mod, maxlen = 70, doc = doc) + '\n')
  1311.                 
  1312.             
  1313.             return attrs
  1314.  
  1315.         attrs = filter((lambda data: visiblename(data[0])), classify_class_attrs(object))
  1316.         while attrs:
  1317.             if mro:
  1318.                 thisclass = mro.popleft()
  1319.             else:
  1320.                 thisclass = attrs[0][2]
  1321.             (attrs, inherited) = _split_list((attrs,), (lambda t: t[2] is thisclass))
  1322.             if thisclass is __builtin__.object:
  1323.                 attrs = inherited
  1324.                 continue
  1325.             elif thisclass is object:
  1326.                 tag = 'defined here'
  1327.             else:
  1328.                 tag = 'inherited from %s' % classname(thisclass, object.__module__)
  1329.             attrs.sort()
  1330.             attrs = spill('Methods %s:\n' % tag, attrs, (lambda t: t[1] == 'method'))
  1331.             attrs = spill('Class methods %s:\n' % tag, attrs, (lambda t: t[1] == 'class method'))
  1332.             attrs = spill('Static methods %s:\n' % tag, attrs, (lambda t: t[1] == 'static method'))
  1333.             attrs = spilldescriptors('Data descriptors %s:\n' % tag, attrs, (lambda t: t[1] == 'data descriptor'))
  1334.             attrs = spilldata('Data and other attributes %s:\n' % tag, attrs, (lambda t: t[1] == 'data'))
  1335.             if not attrs == []:
  1336.                 raise AssertionError
  1337.             attrs = inherited
  1338.             continue
  1339.             attrs == []
  1340.         contents = '\n'.join(contents)
  1341.         if not contents:
  1342.             return title + '\n'
  1343.         return title + '\n' + self.indent(rstrip(contents), ' |  ') + '\n'
  1344.  
  1345.     
  1346.     def formatvalue(self, object):
  1347.         '''Format an argument default value as text.'''
  1348.         return '=' + self.repr(object)
  1349.  
  1350.     
  1351.     def docroutine(self, object, name = None, mod = None, cl = None):
  1352.         '''Produce text documentation for a function or method object.'''
  1353.         realname = object.__name__
  1354.         if not name:
  1355.             pass
  1356.         name = realname
  1357.         note = ''
  1358.         skipdocs = 0
  1359.         if inspect.ismethod(object):
  1360.             imclass = object.im_class
  1361.             if cl:
  1362.                 if imclass is not cl:
  1363.                     note = ' from ' + classname(imclass, mod)
  1364.                 
  1365.             elif object.im_self is not None:
  1366.                 note = ' method of %s instance' % classname(object.im_self.__class__, mod)
  1367.             else:
  1368.                 note = ' unbound %s method' % classname(imclass, mod)
  1369.             object = object.im_func
  1370.         
  1371.         if name == realname:
  1372.             title = self.bold(realname)
  1373.         elif cl and realname in cl.__dict__ and cl.__dict__[realname] is object:
  1374.             skipdocs = 1
  1375.         
  1376.         title = self.bold(name) + ' = ' + realname
  1377.         if inspect.isfunction(object):
  1378.             (args, varargs, varkw, defaults) = inspect.getargspec(object)
  1379.             argspec = inspect.formatargspec(args, varargs, varkw, defaults, formatvalue = self.formatvalue)
  1380.             if realname == '<lambda>':
  1381.                 title = self.bold(name) + ' lambda '
  1382.                 argspec = argspec[1:-1]
  1383.             
  1384.         else:
  1385.             argspec = '(...)'
  1386.         decl = title + argspec + note
  1387.         doc = skipdocs if skipdocs else ''
  1388.         if doc:
  1389.             pass
  1390.         return decl + '\n' + rstrip(self.indent(doc)) + '\n'
  1391.  
  1392.     
  1393.     def _docdescriptor(self, name, value, mod):
  1394.         results = []
  1395.         push = results.append
  1396.         if name:
  1397.             push(self.bold(name))
  1398.             push('\n')
  1399.         
  1400.         if not getdoc(value):
  1401.             pass
  1402.         doc = ''
  1403.         if doc:
  1404.             push(self.indent(doc))
  1405.             push('\n')
  1406.         
  1407.         return ''.join(results)
  1408.  
  1409.     
  1410.     def docproperty(self, object, name = None, mod = None, cl = None):
  1411.         '''Produce text documentation for a property.'''
  1412.         return self._docdescriptor(name, object, mod)
  1413.  
  1414.     
  1415.     def docdata(self, object, name = None, mod = None, cl = None):
  1416.         '''Produce text documentation for a data descriptor.'''
  1417.         return self._docdescriptor(name, object, mod)
  1418.  
  1419.     
  1420.     def docother(self, object, name = None, mod = None, parent = None, maxlen = None, doc = None):
  1421.         '''Produce text documentation for a data object.'''
  1422.         repr = self.repr(object)
  1423.         if maxlen:
  1424.             if not name or name + ' = ':
  1425.                 pass
  1426.             line = '' + repr
  1427.             chop = maxlen - len(line)
  1428.             if chop < 0:
  1429.                 repr = repr[:chop] + '...'
  1430.             
  1431.         
  1432.         if not name or self.bold(name) + ' = ':
  1433.             pass
  1434.         line = '' + repr
  1435.         if doc is not None:
  1436.             line += '\n' + self.indent(str(doc))
  1437.         
  1438.         return line
  1439.  
  1440.  
  1441.  
  1442. def pager(text):
  1443.     '''The first time this is called, determine what kind of pager to use.'''
  1444.     global pager
  1445.     pager = getpager()
  1446.     pager(text)
  1447.  
  1448.  
  1449. def getpager():
  1450.     '''Decide what method to use for paging through text.'''
  1451.     if type(sys.stdout) is not types.FileType:
  1452.         return plainpager
  1453.     if not sys.stdin.isatty() or not sys.stdout.isatty():
  1454.         return plainpager
  1455.     if 'PAGER' in os.environ:
  1456.         if sys.platform == 'win32':
  1457.             return (lambda text: tempfilepager(plain(text), os.environ['PAGER']))
  1458.         if os.environ.get('TERM') in ('dumb', 'emacs'):
  1459.             return (lambda text: pipepager(plain(text), os.environ['PAGER']))
  1460.         return (lambda text: pipepager(text, os.environ['PAGER']))
  1461.     'PAGER' in os.environ
  1462.     if os.environ.get('TERM') in ('dumb', 'emacs'):
  1463.         return plainpager
  1464.     if sys.platform == 'win32' or sys.platform.startswith('os2'):
  1465.         return (lambda text: tempfilepager(plain(text), 'more <'))
  1466.     if hasattr(os, 'system') and os.system('(less) 2>/dev/null') == 0:
  1467.         return (lambda text: pipepager(text, 'less'))
  1468.     import tempfile as tempfile
  1469.     (fd, filename) = tempfile.mkstemp()
  1470.     os.close(fd)
  1471.     
  1472.     try:
  1473.         if hasattr(os, 'system') and os.system('more "%s"' % filename) == 0:
  1474.             return (lambda text: pipepager(text, 'more'))
  1475.         return ttypager
  1476.     finally:
  1477.         os.unlink(filename)
  1478.  
  1479.  
  1480.  
  1481. def plain(text):
  1482.     '''Remove boldface formatting from text.'''
  1483.     return re.sub('.\x08', '', text)
  1484.  
  1485.  
  1486. def pipepager(text, cmd):
  1487.     '''Page through text by feeding it to another program.'''
  1488.     pipe = os.popen(cmd, 'w')
  1489.     
  1490.     try:
  1491.         pipe.write(text)
  1492.         pipe.close()
  1493.     except IOError:
  1494.         pass
  1495.  
  1496.  
  1497.  
  1498. def tempfilepager(text, cmd):
  1499.     '''Page through text by invoking a program on a temporary file.'''
  1500.     import tempfile
  1501.     filename = tempfile.mktemp()
  1502.     file = open(filename, 'w')
  1503.     file.write(text)
  1504.     file.close()
  1505.     
  1506.     try:
  1507.         os.system(cmd + ' "' + filename + '"')
  1508.     finally:
  1509.         os.unlink(filename)
  1510.  
  1511.  
  1512.  
  1513. def ttypager(text):
  1514.     '''Page through text on a text terminal.'''
  1515.     lines = split(plain(text), '\n')
  1516.     
  1517.     try:
  1518.         import tty as tty
  1519.         fd = sys.stdin.fileno()
  1520.         old = tty.tcgetattr(fd)
  1521.         tty.setcbreak(fd)
  1522.         
  1523.         getchar = lambda : sys.stdin.read(1)
  1524.     except (ImportError, AttributeError):
  1525.         tty = None
  1526.         
  1527.         getchar = lambda : sys.stdin.readline()[:-1][:1]
  1528.  
  1529.     
  1530.     try:
  1531.         r = inc = os.environ.get('LINES', 25) - 1
  1532.         sys.stdout.write(join(lines[:inc], '\n') + '\n')
  1533.         while lines[r:]:
  1534.             sys.stdout.write('-- more --')
  1535.             sys.stdout.flush()
  1536.             c = getchar()
  1537.             if c in ('q', 'Q'):
  1538.                 sys.stdout.write('\r          \r')
  1539.                 break
  1540.             elif c in ('\r', '\n'):
  1541.                 sys.stdout.write('\r          \r' + lines[r] + '\n')
  1542.                 r = r + 1
  1543.                 continue
  1544.             
  1545.             if c in ('b', 'B', '\x1b'):
  1546.                 r = r - inc - inc
  1547.                 if r < 0:
  1548.                     r = 0
  1549.                 
  1550.             
  1551.             sys.stdout.write('\n' + join(lines[r:r + inc], '\n') + '\n')
  1552.             r = r + inc
  1553.     finally:
  1554.         if tty:
  1555.             tty.tcsetattr(fd, tty.TCSAFLUSH, old)
  1556.         
  1557.  
  1558.  
  1559.  
  1560. def plainpager(text):
  1561.     '''Simply print unformatted text.  This is the ultimate fallback.'''
  1562.     sys.stdout.write(plain(text))
  1563.  
  1564.  
  1565. def describe(thing):
  1566.     '''Produce a short description of the given thing.'''
  1567.     if inspect.ismodule(thing):
  1568.         if thing.__name__ in sys.builtin_module_names:
  1569.             return 'built-in module ' + thing.__name__
  1570.         if hasattr(thing, '__path__'):
  1571.             return 'package ' + thing.__name__
  1572.         return 'module ' + thing.__name__
  1573.     inspect.ismodule(thing)
  1574.     if inspect.isbuiltin(thing):
  1575.         return 'built-in function ' + thing.__name__
  1576.     if inspect.isgetsetdescriptor(thing):
  1577.         return 'getset descriptor %s.%s.%s' % (thing.__objclass__.__module__, thing.__objclass__.__name__, thing.__name__)
  1578.     if inspect.ismemberdescriptor(thing):
  1579.         return 'member descriptor %s.%s.%s' % (thing.__objclass__.__module__, thing.__objclass__.__name__, thing.__name__)
  1580.     if inspect.isclass(thing):
  1581.         return 'class ' + thing.__name__
  1582.     if inspect.isfunction(thing):
  1583.         return 'function ' + thing.__name__
  1584.     if inspect.ismethod(thing):
  1585.         return 'method ' + thing.__name__
  1586.     if type(thing) is types.InstanceType:
  1587.         return 'instance of ' + thing.__class__.__name__
  1588.     return type(thing).__name__
  1589.  
  1590.  
  1591. def locate(path, forceload = 0):
  1592.     '''Locate an object by name or dotted path, importing as necessary.'''
  1593.     parts = _[1]
  1594.     (module, n) = (None, 0)
  1595.     while n < len(parts):
  1596.         nextmodule = safeimport(join(parts[:n + 1], '.'), forceload)
  1597.         if nextmodule:
  1598.             module = nextmodule
  1599.             n = n + 1
  1600.             continue
  1601.         []
  1602.         break
  1603.         continue
  1604.         []
  1605.     if module:
  1606.         object = module
  1607.         for part in parts[n:]:
  1608.             
  1609.             try:
  1610.                 object = getattr(object, part)
  1611.             continue
  1612.             except AttributeError:
  1613.                 return None
  1614.             
  1615.  
  1616.         
  1617.         return object
  1618.     if hasattr(__builtin__, path):
  1619.         return getattr(__builtin__, path)
  1620.  
  1621. text = TextDoc()
  1622. html = HTMLDoc()
  1623.  
  1624. class _OldStyleClass:
  1625.     pass
  1626.  
  1627. _OLD_INSTANCE_TYPE = type(_OldStyleClass())
  1628.  
  1629. def resolve(thing, forceload = 0):
  1630.     '''Given an object or a path to an object, get the object and its name.'''
  1631.     if isinstance(thing, str):
  1632.         object = locate(thing, forceload)
  1633.         if not object:
  1634.             raise ImportError, 'no Python documentation found for %r' % thing
  1635.         object
  1636.         return (object, thing)
  1637.     return (thing, getattr(thing, '__name__', None))
  1638.  
  1639.  
  1640. def render_doc(thing, title = 'Python Library Documentation: %s', forceload = 0):
  1641.     '''Render text documentation, given an object or a path to an object.'''
  1642.     (object, name) = resolve(thing, forceload)
  1643.     desc = describe(object)
  1644.     module = inspect.getmodule(object)
  1645.     if name and '.' in name:
  1646.         desc += ' in ' + name[:name.rfind('.')]
  1647.     elif module and module is not object:
  1648.         desc += ' in module ' + module.__name__
  1649.     
  1650.     if type(object) is _OLD_INSTANCE_TYPE:
  1651.         object = object.__class__
  1652.     elif not inspect.ismodule(object) and inspect.isclass(object) and inspect.isroutine(object) and inspect.isgetsetdescriptor(object) and inspect.ismemberdescriptor(object) or isinstance(object, property):
  1653.         object = type(object)
  1654.         desc += ' object'
  1655.     
  1656.     return title % desc + '\n\n' + text.document(object, name)
  1657.  
  1658.  
  1659. def doc(thing, title = 'Python Library Documentation: %s', forceload = 0):
  1660.     '''Display text documentation, given an object or a path to an object.'''
  1661.     
  1662.     try:
  1663.         pager(render_doc(thing, title, forceload))
  1664.     except (ImportError, ErrorDuringImport):
  1665.         value = None
  1666.         print value
  1667.  
  1668.  
  1669.  
  1670. def writedoc(thing, forceload = 0):
  1671.     '''Write HTML documentation to a file in the current directory.'''
  1672.     
  1673.     try:
  1674.         (object, name) = resolve(thing, forceload)
  1675.         page = html.page(describe(object), html.document(object, name))
  1676.         file = open(name + '.html', 'w')
  1677.         file.write(page)
  1678.         file.close()
  1679.         print 'wrote', name + '.html'
  1680.     except (ImportError, ErrorDuringImport):
  1681.         value = None
  1682.         print value
  1683.  
  1684.  
  1685.  
  1686. def writedocs(dir, pkgpath = '', done = None):
  1687.     '''Write out HTML documentation for all modules in a directory tree.'''
  1688.     if done is None:
  1689.         done = { }
  1690.     
  1691.     for importer, modname, ispkg in pkgutil.walk_packages([
  1692.         dir], pkgpath):
  1693.         writedoc(modname)
  1694.     
  1695.  
  1696.  
  1697. class Helper:
  1698.     keywords = {
  1699.         'and': 'BOOLEAN',
  1700.         'as': 'with',
  1701.         'assert': ('assert', ''),
  1702.         'break': ('break', 'while for'),
  1703.         'class': ('class', 'CLASSES SPECIALMETHODS'),
  1704.         'continue': ('continue', 'while for'),
  1705.         'def': ('function', ''),
  1706.         'del': ('del', 'BASICMETHODS'),
  1707.         'elif': 'if',
  1708.         'else': ('else', 'while for'),
  1709.         'except': 'try',
  1710.         'exec': ('exec', ''),
  1711.         'finally': 'try',
  1712.         'for': ('for', 'break continue while'),
  1713.         'from': 'import',
  1714.         'global': ('global', 'NAMESPACES'),
  1715.         'if': ('if', 'TRUTHVALUE'),
  1716.         'import': ('import', 'MODULES'),
  1717.         'in': ('in', 'SEQUENCEMETHODS2'),
  1718.         'is': 'COMPARISON',
  1719.         'lambda': ('lambda', 'FUNCTIONS'),
  1720.         'not': 'BOOLEAN',
  1721.         'or': 'BOOLEAN',
  1722.         'pass': ('pass', ''),
  1723.         'print': ('print', ''),
  1724.         'raise': ('raise', 'EXCEPTIONS'),
  1725.         'return': ('return', 'FUNCTIONS'),
  1726.         'try': ('try', 'EXCEPTIONS'),
  1727.         'while': ('while', 'break continue if TRUTHVALUE'),
  1728.         'with': ('with', 'CONTEXTMANAGERS EXCEPTIONS yield'),
  1729.         'yield': ('yield', '') }
  1730.     _symbols_inverse = {
  1731.         'STRINGS': ("'", "'''", "r'", "u'", '"""', '"', 'r"', 'u"'),
  1732.         'OPERATORS': ('+', '-', '*', '**', '/', '//', '%', '<<', '>>', '&', '|', '^', '~', '<', '>', '<=', '>=', '==', '!=', '<>'),
  1733.         'COMPARISON': ('<', '>', '<=', '>=', '==', '!=', '<>'),
  1734.         'UNARY': ('-', '~'),
  1735.         'AUGMENTEDASSIGNMENT': ('+=', '-=', '*=', '/=', '%=', '&=', '|=', '^=', '<<=', '>>=', '**=', '//='),
  1736.         'BITWISE': ('<<', '>>', '&', '|', '^', '~'),
  1737.         'COMPLEX': ('j', 'J') }
  1738.     symbols = {
  1739.         '%': 'OPERATORS FORMATTING',
  1740.         '**': 'POWER',
  1741.         ',': 'TUPLES LISTS FUNCTIONS',
  1742.         '.': 'ATTRIBUTES FLOAT MODULES OBJECTS',
  1743.         '...': 'ELLIPSIS',
  1744.         ':': 'SLICINGS DICTIONARYLITERALS',
  1745.         '@': 'def class',
  1746.         '\\': 'STRINGS',
  1747.         '_': 'PRIVATENAMES',
  1748.         '__': 'PRIVATENAMES SPECIALMETHODS',
  1749.         '`': 'BACKQUOTES',
  1750.         '(': 'TUPLES FUNCTIONS CALLS',
  1751.         ')': 'TUPLES FUNCTIONS CALLS',
  1752.         '[': 'LISTS SUBSCRIPTS SLICINGS',
  1753.         ']': 'LISTS SUBSCRIPTS SLICINGS' }
  1754.     for topic, symbols_ in _symbols_inverse.iteritems():
  1755.         for symbol in symbols_:
  1756.             topics = symbols.get(symbol, topic)
  1757.             if topic not in topics:
  1758.                 topics = topics + ' ' + topic
  1759.             
  1760.             symbols[symbol] = topics
  1761.         
  1762.     
  1763.     topics = {
  1764.         'TYPES': ('types', 'STRINGS UNICODE NUMBERS SEQUENCES MAPPINGS FUNCTIONS CLASSES MODULES FILES inspect'),
  1765.         'STRINGS': ('strings', 'str UNICODE SEQUENCES STRINGMETHODS FORMATTING TYPES'),
  1766.         'STRINGMETHODS': ('string-methods', 'STRINGS FORMATTING'),
  1767.         'FORMATTING': ('formatstrings', 'OPERATORS'),
  1768.         'UNICODE': ('strings', 'encodings unicode SEQUENCES STRINGMETHODS FORMATTING TYPES'),
  1769.         'NUMBERS': ('numbers', 'INTEGER FLOAT COMPLEX TYPES'),
  1770.         'INTEGER': ('integers', 'int range'),
  1771.         'FLOAT': ('floating', 'float math'),
  1772.         'COMPLEX': ('imaginary', 'complex cmath'),
  1773.         'SEQUENCES': ('typesseq', 'STRINGMETHODS FORMATTING xrange LISTS'),
  1774.         'MAPPINGS': 'DICTIONARIES',
  1775.         'FUNCTIONS': ('typesfunctions', 'def TYPES'),
  1776.         'METHODS': ('typesmethods', 'class def CLASSES TYPES'),
  1777.         'CODEOBJECTS': ('bltin-code-objects', 'compile FUNCTIONS TYPES'),
  1778.         'TYPEOBJECTS': ('bltin-type-objects', 'types TYPES'),
  1779.         'FRAMEOBJECTS': 'TYPES',
  1780.         'TRACEBACKS': 'TYPES',
  1781.         'NONE': ('bltin-null-object', ''),
  1782.         'ELLIPSIS': ('bltin-ellipsis-object', 'SLICINGS'),
  1783.         'FILES': ('bltin-file-objects', ''),
  1784.         'SPECIALATTRIBUTES': ('specialattrs', ''),
  1785.         'CLASSES': ('types', 'class SPECIALMETHODS PRIVATENAMES'),
  1786.         'MODULES': ('typesmodules', 'import'),
  1787.         'PACKAGES': 'import',
  1788.         'EXPRESSIONS': ('operator-summary', 'lambda or and not in is BOOLEAN COMPARISON BITWISE SHIFTING BINARY FORMATTING POWER UNARY ATTRIBUTES SUBSCRIPTS SLICINGS CALLS TUPLES LISTS DICTIONARIES BACKQUOTES'),
  1789.         'OPERATORS': 'EXPRESSIONS',
  1790.         'PRECEDENCE': 'EXPRESSIONS',
  1791.         'OBJECTS': ('objects', 'TYPES'),
  1792.         'SPECIALMETHODS': ('specialnames', 'BASICMETHODS ATTRIBUTEMETHODS CALLABLEMETHODS SEQUENCEMETHODS1 MAPPINGMETHODS SEQUENCEMETHODS2 NUMBERMETHODS CLASSES'),
  1793.         'BASICMETHODS': ('customization', 'cmp hash repr str SPECIALMETHODS'),
  1794.         'ATTRIBUTEMETHODS': ('attribute-access', 'ATTRIBUTES SPECIALMETHODS'),
  1795.         'CALLABLEMETHODS': ('callable-types', 'CALLS SPECIALMETHODS'),
  1796.         'SEQUENCEMETHODS1': ('sequence-types', 'SEQUENCES SEQUENCEMETHODS2 SPECIALMETHODS'),
  1797.         'SEQUENCEMETHODS2': ('sequence-methods', 'SEQUENCES SEQUENCEMETHODS1 SPECIALMETHODS'),
  1798.         'MAPPINGMETHODS': ('sequence-types', 'MAPPINGS SPECIALMETHODS'),
  1799.         'NUMBERMETHODS': ('numeric-types', 'NUMBERS AUGMENTEDASSIGNMENT SPECIALMETHODS'),
  1800.         'EXECUTION': ('execmodel', 'NAMESPACES DYNAMICFEATURES EXCEPTIONS'),
  1801.         'NAMESPACES': ('naming', 'global ASSIGNMENT DELETION DYNAMICFEATURES'),
  1802.         'DYNAMICFEATURES': ('dynamic-features', ''),
  1803.         'SCOPING': 'NAMESPACES',
  1804.         'FRAMES': 'NAMESPACES',
  1805.         'EXCEPTIONS': ('exceptions', 'try except finally raise'),
  1806.         'COERCIONS': ('coercion-rules', 'CONVERSIONS'),
  1807.         'CONVERSIONS': ('conversions', 'COERCIONS'),
  1808.         'IDENTIFIERS': ('identifiers', 'keywords SPECIALIDENTIFIERS'),
  1809.         'SPECIALIDENTIFIERS': ('id-classes', ''),
  1810.         'PRIVATENAMES': ('atom-identifiers', ''),
  1811.         'LITERALS': ('atom-literals', 'STRINGS BACKQUOTES NUMBERS TUPLELITERALS LISTLITERALS DICTIONARYLITERALS'),
  1812.         'TUPLES': 'SEQUENCES',
  1813.         'TUPLELITERALS': ('exprlists', 'TUPLES LITERALS'),
  1814.         'LISTS': ('typesseq-mutable', 'LISTLITERALS'),
  1815.         'LISTLITERALS': ('lists', 'LISTS LITERALS'),
  1816.         'DICTIONARIES': ('typesmapping', 'DICTIONARYLITERALS'),
  1817.         'DICTIONARYLITERALS': ('dict', 'DICTIONARIES LITERALS'),
  1818.         'BACKQUOTES': ('string-conversions', 'repr str STRINGS LITERALS'),
  1819.         'ATTRIBUTES': ('attribute-references', 'getattr hasattr setattr ATTRIBUTEMETHODS'),
  1820.         'SUBSCRIPTS': ('subscriptions', 'SEQUENCEMETHODS1'),
  1821.         'SLICINGS': ('slicings', 'SEQUENCEMETHODS2'),
  1822.         'CALLS': ('calls', 'EXPRESSIONS'),
  1823.         'POWER': ('power', 'EXPRESSIONS'),
  1824.         'UNARY': ('unary', 'EXPRESSIONS'),
  1825.         'BINARY': ('binary', 'EXPRESSIONS'),
  1826.         'SHIFTING': ('shifting', 'EXPRESSIONS'),
  1827.         'BITWISE': ('bitwise', 'EXPRESSIONS'),
  1828.         'COMPARISON': ('comparisons', 'EXPRESSIONS BASICMETHODS'),
  1829.         'BOOLEAN': ('booleans', 'EXPRESSIONS TRUTHVALUE'),
  1830.         'ASSERTION': 'assert',
  1831.         'ASSIGNMENT': ('assignment', 'AUGMENTEDASSIGNMENT'),
  1832.         'AUGMENTEDASSIGNMENT': ('augassign', 'NUMBERMETHODS'),
  1833.         'DELETION': 'del',
  1834.         'PRINTING': 'print',
  1835.         'RETURNING': 'return',
  1836.         'IMPORTING': 'import',
  1837.         'CONDITIONAL': 'if',
  1838.         'LOOPING': ('compound', 'for while break continue'),
  1839.         'TRUTHVALUE': ('truth', 'if while and or not BASICMETHODS'),
  1840.         'DEBUGGING': ('debugger', 'pdb'),
  1841.         'CONTEXTMANAGERS': ('context-managers', 'with') }
  1842.     
  1843.     def __init__(self, input, output):
  1844.         self.input = input
  1845.         self.output = output
  1846.  
  1847.     
  1848.     def __repr__(self):
  1849.         if inspect.stack()[1][3] == '?':
  1850.             self()
  1851.             return ''
  1852.         return '<pydoc.Helper instance>'
  1853.  
  1854.     
  1855.     def __call__(self, request = None):
  1856.         if request is not None:
  1857.             self.help(request)
  1858.         else:
  1859.             self.intro()
  1860.             self.interact()
  1861.             self.output.write('\nYou are now leaving help and returning to the Python interpreter.\nIf you want to ask for help on a particular object directly from the\ninterpreter, you can type "help(object)".  Executing "help(\'string\')"\nhas the same effect as typing a particular string at the help> prompt.\n')
  1862.  
  1863.     
  1864.     def interact(self):
  1865.         self.output.write('\n')
  1866.         while True:
  1867.             
  1868.             try:
  1869.                 request = self.getline('help> ')
  1870.                 if not request:
  1871.                     break
  1872.             except (KeyboardInterrupt, EOFError):
  1873.                 break
  1874.  
  1875.             request = strip(replace(request, '"', '', "'", ''))
  1876.             if lower(request) in ('q', 'quit'):
  1877.                 break
  1878.             
  1879.             self.help(request)
  1880.  
  1881.     
  1882.     def getline(self, prompt):
  1883.         '''Read one line, using raw_input when available.'''
  1884.         if self.input is sys.stdin:
  1885.             return raw_input(prompt)
  1886.         self.output.write(prompt)
  1887.         self.output.flush()
  1888.         return self.input.readline()
  1889.  
  1890.     
  1891.     def help(self, request):
  1892.         if type(request) is type(''):
  1893.             request = request.strip()
  1894.             if request == 'help':
  1895.                 self.intro()
  1896.             elif request == 'keywords':
  1897.                 self.listkeywords()
  1898.             elif request == 'symbols':
  1899.                 self.listsymbols()
  1900.             elif request == 'topics':
  1901.                 self.listtopics()
  1902.             elif request == 'modules':
  1903.                 self.listmodules()
  1904.             elif request[:8] == 'modules ':
  1905.                 self.listmodules(split(request)[1])
  1906.             elif request in self.symbols:
  1907.                 self.showsymbol(request)
  1908.             elif request in self.keywords:
  1909.                 self.showtopic(request)
  1910.             elif request in self.topics:
  1911.                 self.showtopic(request)
  1912.             elif request:
  1913.                 doc(request, 'Help on %s:')
  1914.             
  1915.         elif isinstance(request, Helper):
  1916.             self()
  1917.         else:
  1918.             doc(request, 'Help on %s:')
  1919.         self.output.write('\n')
  1920.  
  1921.     
  1922.     def intro(self):
  1923.         self.output.write('\nWelcome to Python %s!  This is the online help utility.\n\nIf this is your first time using Python, you should definitely check out\nthe tutorial on the Internet at http://docs.python.org/tutorial/.\n\nEnter the name of any module, keyword, or topic to get help on writing\nPython programs and using Python modules.  To quit this help utility and\nreturn to the interpreter, just type "quit".\n\nTo get a list of available modules, keywords, or topics, type "modules",\n"keywords", or "topics".  Each module also comes with a one-line summary\nof what it does; to list the modules whose summaries contain a given word\nsuch as "spam", type "modules spam".\n' % sys.version[:3])
  1924.  
  1925.     
  1926.     def list(self, items, columns = 4, width = 80):
  1927.         items = items[:]
  1928.         items.sort()
  1929.         colw = width / columns
  1930.         rows = (len(items) + columns - 1) / columns
  1931.         for row in range(rows):
  1932.             for col in range(columns):
  1933.                 i = col * rows + row
  1934.                 if i < len(items):
  1935.                     self.output.write(items[i])
  1936.                     if col < columns - 1:
  1937.                         self.output.write(' ' + ' ' * (colw - 1 - len(items[i])))
  1938.                     
  1939.                 col < columns - 1
  1940.             
  1941.             self.output.write('\n')
  1942.         
  1943.  
  1944.     
  1945.     def listkeywords(self):
  1946.         self.output.write('\nHere is a list of the Python keywords.  Enter any keyword to get more help.\n\n')
  1947.         self.list(self.keywords.keys())
  1948.  
  1949.     
  1950.     def listsymbols(self):
  1951.         self.output.write('\nHere is a list of the punctuation symbols which Python assigns special meaning\nto. Enter any symbol to get more help.\n\n')
  1952.         self.list(self.symbols.keys())
  1953.  
  1954.     
  1955.     def listtopics(self):
  1956.         self.output.write('\nHere is a list of available topics.  Enter any topic name to get more help.\n\n')
  1957.         self.list(self.topics.keys())
  1958.  
  1959.     
  1960.     def showtopic(self, topic, more_xrefs = ''):
  1961.         
  1962.         try:
  1963.             import pydoc_topics as pydoc_topics
  1964.         except ImportError:
  1965.             self.output.write('\nSorry, topic and keyword documentation is not available because the\nmodule "pydoc_topics" could not be found.\n')
  1966.             return None
  1967.  
  1968.         target = self.topics.get(topic, self.keywords.get(topic))
  1969.         if not target:
  1970.             self.output.write('no documentation found for %s\n' % repr(topic))
  1971.             return None
  1972.         if type(target) is type(''):
  1973.             return self.showtopic(target, more_xrefs)
  1974.         (label, xrefs) = target
  1975.         
  1976.         try:
  1977.             doc = pydoc_topics.topics[label]
  1978.         except KeyError:
  1979.             type(target) is type('')
  1980.             type(target) is type('')
  1981.             target
  1982.             self.output.write('no documentation found for %s\n' % repr(topic))
  1983.             return None
  1984.  
  1985.         pager(strip(doc) + '\n')
  1986.         if xrefs:
  1987.             import StringIO as StringIO
  1988.             import formatter as formatter
  1989.             buffer = StringIO.StringIO()
  1990.             formatter.DumbWriter(buffer).send_flowing_data('Related help topics: ' + join(split(xrefs), ', ') + '\n')
  1991.             self.output.write('\n%s\n' % buffer.getvalue())
  1992.         
  1993.  
  1994.     
  1995.     def showsymbol(self, symbol):
  1996.         target = self.symbols[symbol]
  1997.         (topic, _, xrefs) = target.partition(' ')
  1998.         self.showtopic(topic, xrefs)
  1999.  
  2000.     
  2001.     def listmodules(self, key = ''):
  2002.         pass
  2003.  
  2004.  
  2005. help = Helper(sys.stdin, sys.stdout)
  2006.  
  2007. class Scanner:
  2008.     '''A generic tree iterator.'''
  2009.     
  2010.     def __init__(self, roots, children, descendp):
  2011.         self.roots = roots[:]
  2012.         self.state = []
  2013.         self.children = children
  2014.         self.descendp = descendp
  2015.  
  2016.     
  2017.     def next(self):
  2018.         if not self.state:
  2019.             if not self.roots:
  2020.                 return None
  2021.             root = self.roots.pop(0)
  2022.             self.state = [
  2023.                 (root, self.children(root))]
  2024.         
  2025.         (node, children) = self.state[-1]
  2026.         if not children:
  2027.             self.state.pop()
  2028.             return self.next()
  2029.         child = children.pop(0)
  2030.         if self.descendp(child):
  2031.             self.state.append((child, self.children(child)))
  2032.         
  2033.         return child
  2034.  
  2035.  
  2036.  
  2037. class ModuleScanner:
  2038.     '''An interruptible scanner that searches module synopses.'''
  2039.     
  2040.     def run(self, callback, key = None, completer = None, onerror = None):
  2041.         if key:
  2042.             key = lower(key)
  2043.         
  2044.         self.quit = False
  2045.         seen = { }
  2046.         for modname in sys.builtin_module_names:
  2047.             if modname != '__main__':
  2048.                 seen[modname] = 1
  2049.                 desc = None(split if key is None else '', '\n')[0]
  2050.                 if find(lower(modname + ' - ' + desc), key) >= 0:
  2051.                     callback(None, modname, desc)
  2052.                 
  2053.             find(lower(modname + ' - ' + desc), key) >= 0
  2054.         
  2055.         for importer, modname, ispkg in pkgutil.walk_packages(onerror = onerror):
  2056.             if self.quit:
  2057.                 break
  2058.             
  2059.             if key is None:
  2060.                 callback(None, modname, '')
  2061.                 continue
  2062.             loader = importer.find_module(modname)
  2063.             if hasattr(loader, 'get_source'):
  2064.                 import StringIO
  2065.                 if not source_synopsis(StringIO.StringIO(loader.get_source(modname))):
  2066.                     pass
  2067.                 desc = ''
  2068.                 if hasattr(loader, 'get_filename'):
  2069.                     path = loader.get_filename(modname)
  2070.                 else:
  2071.                     path = None
  2072.             else:
  2073.                 module = loader.load_module(modname)
  2074.                 if not module.__doc__:
  2075.                     pass
  2076.                 desc = ''.splitlines()[0]
  2077.                 path = getattr(module, '__file__', None)
  2078.             if find(lower(modname + ' - ' + desc), key) >= 0:
  2079.                 callback(path, modname, desc)
  2080.                 continue
  2081.         
  2082.         if completer:
  2083.             completer()
  2084.         
  2085.  
  2086.  
  2087.  
  2088. def apropos(key):
  2089.     '''Print all the one-line module summaries that contain a substring.'''
  2090.     
  2091.     def callback(path, modname, desc):
  2092.         if modname[-9:] == '.__init__':
  2093.             modname = modname[:-9] + ' (package)'
  2094.         
  2095.         print modname,
  2096.         if desc:
  2097.             pass
  2098.         print '- ' + desc
  2099.  
  2100.     
  2101.     try:
  2102.         import warnings as warnings
  2103.     except ImportError:
  2104.         pass
  2105.  
  2106.     warnings.filterwarnings('ignore')
  2107.     ModuleScanner().run(callback, key)
  2108.  
  2109.  
  2110. def serve(port, callback = None, completer = None):
  2111.     import BaseHTTPServer as BaseHTTPServer
  2112.     import mimetools as mimetools
  2113.     import select
  2114.     
  2115.     class Message(mimetools.Message):
  2116.         
  2117.         def __init__(self, fp, seekable = 1):
  2118.             Message = self.__class__
  2119.             Message.__bases__[0].__bases__[0].__init__(self, fp, seekable)
  2120.             self.encodingheader = self.getheader('content-transfer-encoding')
  2121.             self.typeheader = self.getheader('content-type')
  2122.             self.parsetype()
  2123.             self.parseplist()
  2124.  
  2125.  
  2126.     
  2127.     class DocHandler(BaseHTTPServer.BaseHTTPRequestHandler):
  2128.         
  2129.         def send_document(self, title, contents):
  2130.             
  2131.             try:
  2132.                 self.send_response(200)
  2133.                 self.send_header('Content-Type', 'text/html')
  2134.                 self.end_headers()
  2135.                 self.wfile.write(html.page(title, contents))
  2136.             except IOError:
  2137.                 pass
  2138.  
  2139.  
  2140.         
  2141.         def do_GET(self):
  2142.             path = self.path
  2143.             if path[-5:] == '.html':
  2144.                 path = path[:-5]
  2145.             
  2146.             if path[:1] == '/':
  2147.                 path = path[1:]
  2148.             
  2149.             if path and path != '.':
  2150.                 
  2151.                 try:
  2152.                     obj = locate(path, forceload = 1)
  2153.                 except ErrorDuringImport:
  2154.                     value = None
  2155.                     self.send_document(path, html.escape(str(value)))
  2156.                     return None
  2157.  
  2158.                 if obj:
  2159.                     self.send_document(describe(obj), html.document(obj, path))
  2160.                 else:
  2161.                     self.send_document(path, 'no Python documentation found for %s' % repr(path))
  2162.             else:
  2163.                 heading = html.heading('<big><big><strong>Python: Index of Modules</strong></big></big>', '#ffffff', '#7799ee')
  2164.                 
  2165.                 def bltinlink(name):
  2166.                     return '<a href="%s.html">%s</a>' % (name, name)
  2167.  
  2168.                 names = filter((lambda x: x != '__main__'), sys.builtin_module_names)
  2169.                 contents = html.multicolumn(names, bltinlink)
  2170.                 indices = [
  2171.                     '<p>' + html.bigsection('Built-in Modules', '#ffffff', '#ee77aa', contents)]
  2172.                 seen = { }
  2173.                 for dir in sys.path:
  2174.                     indices.append(html.index(dir, seen))
  2175.                 
  2176.                 contents = heading + join(indices) + '<p align=right>\n<font color="#909090" face="helvetica, arial"><strong>\npydoc</strong> by Ka-Ping Yee <ping@lfw.org></font>'
  2177.                 self.send_document('Index of Modules', contents)
  2178.  
  2179.         
  2180.         def log_message(self, *args):
  2181.             pass
  2182.  
  2183.  
  2184.     
  2185.     class DocServer(BaseHTTPServer.HTTPServer):
  2186.         
  2187.         def __init__(self, port, callback):
  2188.             if not sys.platform == 'mac' or '127.0.0.1':
  2189.                 pass
  2190.             host = 'localhost'
  2191.             self.address = ('', port)
  2192.             self.url = 'http://%s:%d/' % (host, port)
  2193.             self.callback = callback
  2194.             self.base.__init__(self, self.address, self.handler)
  2195.  
  2196.         
  2197.         def serve_until_quit(self):
  2198.             import select as select
  2199.             self.quit = False
  2200.             while not self.quit:
  2201.                 (rd, wr, ex) = select.select([
  2202.                     self.socket.fileno()], [], [], 1)
  2203.                 if rd:
  2204.                     self.handle_request()
  2205.                     continue
  2206.  
  2207.         
  2208.         def server_activate(self):
  2209.             self.base.server_activate(self)
  2210.             if self.callback:
  2211.                 self.callback(self)
  2212.             
  2213.  
  2214.  
  2215.     DocServer.base = BaseHTTPServer.HTTPServer
  2216.     DocServer.handler = DocHandler
  2217.     DocHandler.MessageClass = Message
  2218.     
  2219.     try:
  2220.         DocServer(port, callback).serve_until_quit()
  2221.     except (KeyboardInterrupt, select.error):
  2222.         pass
  2223.     finally:
  2224.         if completer:
  2225.             completer()
  2226.         
  2227.  
  2228.  
  2229.  
  2230. def gui():
  2231.     '''Graphical interface (starts web server and pops up a control window).'''
  2232.     
  2233.     class GUI:
  2234.         
  2235.         def __init__(self, window, port = 7464):
  2236.             self.window = window
  2237.             self.server = None
  2238.             self.scanner = None
  2239.             import Tkinter as Tkinter
  2240.             self.server_frm = Tkinter.Frame(window)
  2241.             self.title_lbl = Tkinter.Label(self.server_frm, text = 'Starting server...\n ')
  2242.             self.open_btn = Tkinter.Button(self.server_frm, text = 'open browser', command = self.open, state = 'disabled')
  2243.             self.quit_btn = Tkinter.Button(self.server_frm, text = 'quit serving', command = self.quit, state = 'disabled')
  2244.             self.search_frm = Tkinter.Frame(window)
  2245.             self.search_lbl = Tkinter.Label(self.search_frm, text = 'Search for')
  2246.             self.search_ent = Tkinter.Entry(self.search_frm)
  2247.             self.search_ent.bind('<Return>', self.search)
  2248.             self.stop_btn = Tkinter.Button(self.search_frm, text = 'stop', pady = 0, command = self.stop, state = 'disabled')
  2249.             if sys.platform == 'win32':
  2250.                 self.stop_btn.pack(side = 'right')
  2251.             
  2252.             self.window.title('pydoc')
  2253.             self.window.protocol('WM_DELETE_WINDOW', self.quit)
  2254.             self.title_lbl.pack(side = 'top', fill = 'x')
  2255.             self.open_btn.pack(side = 'left', fill = 'x', expand = 1)
  2256.             self.quit_btn.pack(side = 'right', fill = 'x', expand = 1)
  2257.             self.server_frm.pack(side = 'top', fill = 'x')
  2258.             self.search_lbl.pack(side = 'left')
  2259.             self.search_ent.pack(side = 'right', fill = 'x', expand = 1)
  2260.             self.search_frm.pack(side = 'top', fill = 'x')
  2261.             self.search_ent.focus_set()
  2262.             if not sys.platform == 'win32' or 8:
  2263.                 pass
  2264.             font = ('helvetica', 10)
  2265.             self.result_lst = Tkinter.Listbox(window, font = font, height = 6)
  2266.             self.result_lst.bind('<Button-1>', self.select)
  2267.             self.result_lst.bind('<Double-Button-1>', self.goto)
  2268.             self.result_scr = Tkinter.Scrollbar(window, orient = 'vertical', command = self.result_lst.yview)
  2269.             self.result_lst.config(yscrollcommand = self.result_scr.set)
  2270.             self.result_frm = Tkinter.Frame(window)
  2271.             self.goto_btn = Tkinter.Button(self.result_frm, text = 'go to selected', command = self.goto)
  2272.             self.hide_btn = Tkinter.Button(self.result_frm, text = 'hide results', command = self.hide)
  2273.             self.goto_btn.pack(side = 'left', fill = 'x', expand = 1)
  2274.             self.hide_btn.pack(side = 'right', fill = 'x', expand = 1)
  2275.             self.window.update()
  2276.             self.minwidth = self.window.winfo_width()
  2277.             self.minheight = self.window.winfo_height()
  2278.             self.bigminheight = self.server_frm.winfo_reqheight() + self.search_frm.winfo_reqheight() + self.result_lst.winfo_reqheight() + self.result_frm.winfo_reqheight()
  2279.             self.bigwidth = self.minwidth
  2280.             self.bigheight = self.bigminheight
  2281.             self.expanded = 0
  2282.             self.window.wm_geometry('%dx%d' % (self.minwidth, self.minheight))
  2283.             self.window.wm_minsize(self.minwidth, self.minheight)
  2284.             self.window.tk.willdispatch()
  2285.             import threading as threading
  2286.             threading.Thread(target = serve, args = (port, self.ready, self.quit)).start()
  2287.  
  2288.         
  2289.         def ready(self, server):
  2290.             self.server = server
  2291.             self.title_lbl.config(text = 'Python documentation server at\n' + server.url)
  2292.             self.open_btn.config(state = 'normal')
  2293.             self.quit_btn.config(state = 'normal')
  2294.  
  2295.         
  2296.         def open(self, event = None, url = None):
  2297.             if not url:
  2298.                 pass
  2299.             url = self.server.url
  2300.             
  2301.             try:
  2302.                 import webbrowser as webbrowser
  2303.                 webbrowser.open(url)
  2304.             except ImportError:
  2305.                 if sys.platform == 'win32':
  2306.                     os.system('start "%s"' % url)
  2307.                 elif sys.platform == 'mac':
  2308.                     
  2309.                     try:
  2310.                         import ic as ic
  2311.                     except ImportError:
  2312.                         pass
  2313.  
  2314.                     ic.launchurl(url)
  2315.                 else:
  2316.                     rc = os.system('netscape -remote "openURL(%s)" &' % url)
  2317.                     if rc:
  2318.                         os.system('netscape "%s" &' % url)
  2319.                     
  2320.             except:
  2321.                 sys.platform == 'win32'
  2322.  
  2323.  
  2324.         
  2325.         def quit(self, event = None):
  2326.             if self.server:
  2327.                 self.server.quit = 1
  2328.             
  2329.             self.window.quit()
  2330.  
  2331.         
  2332.         def search(self, event = None):
  2333.             key = self.search_ent.get()
  2334.             self.stop_btn.pack(side = 'right')
  2335.             self.stop_btn.config(state = 'normal')
  2336.             self.search_lbl.config(text = 'Searching for "%s"...' % key)
  2337.             self.search_ent.forget()
  2338.             self.search_lbl.pack(side = 'left')
  2339.             self.result_lst.delete(0, 'end')
  2340.             self.goto_btn.config(state = 'disabled')
  2341.             self.expand()
  2342.             import threading
  2343.             if self.scanner:
  2344.                 self.scanner.quit = 1
  2345.             
  2346.             self.scanner = ModuleScanner()
  2347.             threading.Thread(target = self.scanner.run, args = (self.update, key, self.done)).start()
  2348.  
  2349.         
  2350.         def update(self, path, modname, desc):
  2351.             if modname[-9:] == '.__init__':
  2352.                 modname = modname[:-9] + ' (package)'
  2353.             
  2354.             if not desc:
  2355.                 pass
  2356.             self.result_lst.insert('end', modname + ' - ' + '(no description)')
  2357.  
  2358.         
  2359.         def stop(self, event = None):
  2360.             if self.scanner:
  2361.                 self.scanner.quit = 1
  2362.                 self.scanner = None
  2363.             
  2364.  
  2365.         
  2366.         def done(self):
  2367.             self.scanner = None
  2368.             self.search_lbl.config(text = 'Search for')
  2369.             self.search_lbl.pack(side = 'left')
  2370.             self.search_ent.pack(side = 'right', fill = 'x', expand = 1)
  2371.             if sys.platform != 'win32':
  2372.                 self.stop_btn.forget()
  2373.             
  2374.             self.stop_btn.config(state = 'disabled')
  2375.  
  2376.         
  2377.         def select(self, event = None):
  2378.             self.goto_btn.config(state = 'normal')
  2379.  
  2380.         
  2381.         def goto(self, event = None):
  2382.             selection = self.result_lst.curselection()
  2383.             if selection:
  2384.                 modname = split(self.result_lst.get(selection[0]))[0]
  2385.                 self.open(url = self.server.url + modname + '.html')
  2386.             
  2387.  
  2388.         
  2389.         def collapse(self):
  2390.             if not self.expanded:
  2391.                 return None
  2392.             self.result_frm.forget()
  2393.             self.result_scr.forget()
  2394.             self.result_lst.forget()
  2395.             self.bigwidth = self.window.winfo_width()
  2396.             self.bigheight = self.window.winfo_height()
  2397.             self.window.wm_geometry('%dx%d' % (self.minwidth, self.minheight))
  2398.             self.window.wm_minsize(self.minwidth, self.minheight)
  2399.             self.expanded = 0
  2400.  
  2401.         
  2402.         def expand(self):
  2403.             if self.expanded:
  2404.                 return None
  2405.             self.result_frm.pack(side = 'bottom', fill = 'x')
  2406.             self.result_scr.pack(side = 'right', fill = 'y')
  2407.             self.result_lst.pack(side = 'top', fill = 'both', expand = 1)
  2408.             self.window.wm_geometry('%dx%d' % (self.bigwidth, self.bigheight))
  2409.             self.window.wm_minsize(self.minwidth, self.bigminheight)
  2410.             self.expanded = 1
  2411.  
  2412.         
  2413.         def hide(self, event = None):
  2414.             self.stop()
  2415.             self.collapse()
  2416.  
  2417.  
  2418.     import Tkinter
  2419.     
  2420.     try:
  2421.         root = Tkinter.Tk()
  2422.         
  2423.         try:
  2424.             gui = GUI(root)
  2425.             root.mainloop()
  2426.         finally:
  2427.             root.destroy()
  2428.  
  2429.     except KeyboardInterrupt:
  2430.         pass
  2431.  
  2432.  
  2433.  
  2434. def ispath(x):
  2435.     if isinstance(x, str):
  2436.         pass
  2437.     return find(x, os.sep) >= 0
  2438.  
  2439.  
  2440. def cli():
  2441.     '''Command-line interface (looks at sys.argv to decide what to do).'''
  2442.     import getopt as getopt
  2443.     
  2444.     class BadUsage:
  2445.         pass
  2446.  
  2447.     scriptdir = os.path.dirname(sys.argv[0])
  2448.     if scriptdir in sys.path:
  2449.         sys.path.remove(scriptdir)
  2450.     
  2451.     sys.path.insert(0, '.')
  2452.     
  2453.     try:
  2454.         (opts, args) = getopt.getopt(sys.argv[1:], 'gk:p:w')
  2455.         writing = 0
  2456.         for opt, val in opts:
  2457.             if opt == '-g':
  2458.                 gui()
  2459.                 return None
  2460.             if opt == '-k':
  2461.                 apropos(val)
  2462.                 return None
  2463.             opt == '-k' if opt == '-p' else opt == '-p'
  2464.         
  2465.         if not args:
  2466.             raise BadUsage
  2467.         args
  2468.         for arg in args:
  2469.             
  2470.             try:
  2471.                 if ispath(arg) and os.path.isfile(arg):
  2472.                     arg = importfile(arg)
  2473.                 
  2474.                 if writing:
  2475.                     if ispath(arg) and os.path.isdir(arg):
  2476.                         writedocs(arg)
  2477.                     else:
  2478.                         writedoc(arg)
  2479.                 else:
  2480.                     help.help(arg)
  2481.             continue
  2482.             except ErrorDuringImport:
  2483.                 None if ispath(arg) and not os.path.exists(arg) else opt == '-g'
  2484.                 value = None if ispath(arg) and not os.path.exists(arg) else opt == '-g'
  2485.                 print value
  2486.                 continue
  2487.             
  2488.  
  2489.     except (getopt.error, BadUsage):
  2490.         cmd = os.path.basename(sys.argv[0])
  2491.         print "pydoc - the Python documentation tool\n\n%s <name> ...\n    Show text documentation on something.  <name> may be the name of a\n    Python keyword, topic, function, module, or package, or a dotted\n    reference to a class or function within a module or module in a\n    package.  If <name> contains a '%s', it is used as the path to a\n    Python source file to document. If name is 'keywords', 'topics',\n    or 'modules', a listing of these things is displayed.\n\n%s -k <keyword>\n    Search for a keyword in the synopsis lines of all available modules.\n\n%s -p <port>\n    Start an HTTP server on the given port on the local machine.\n\n%s -g\n    Pop up a graphical interface for finding and serving documentation.\n\n%s -w <name> ...\n    Write out the HTML documentation for a module to a file in the current\n    directory.  If <name> contains a '%s', it is treated as a filename; if\n    it names a directory, documentation is written for all the contents.\n" % (cmd, os.sep, cmd, cmd, cmd, cmd, os.sep)
  2492.  
  2493.  
  2494. if __name__ == '__main__':
  2495.     cli()
  2496.  
  2497.